我正在尝试读取包含以下数据的JSON文件
"{\"studentData\":[{\"Name\":\"Graham\",\"aggregate\":\"86\",\"regular\":\"true\",\"percentages\":[{\"sub1\":\"69\",\"sub2\":\"97\",\"sub3\":\"90\"}]},{\"Name\":\"Finley\",\"aggregate\":\"96\",\"regular\":\"false\",\"percentages\":[{\"sub1\":\"95\",\"sub2\":\"91\",\"sub3\":\"73\"}]},{\"Name\":\"Carrillo\",\"aggregate\":\"93\",\"regular\":\"true\",\"percentages\":[{\"sub1\":\"90\",\"sub2\":\"84\",\"sub3\":\"80\"}]},{\"Name\":\"Crosby\",\"aggregate\":\"68\",\"regular\":\"true\",\"percentages\":[{\"sub1\":\"63\",\"sub2\":\"92\",\"sub3\":\"77\"}]},{\"Name\":\"Small\",\"aggregate\":\"88\",\"regular\":\"true\",\"percentages\":[{\"sub1\":\"65\",\"sub2\":\"80\",\"sub3\":\"81\"}]}]}"
到目前为止,我有以下代码
const data = require("./testdata.json");
/*Explore the JSON file and return required JSON data*/
console.log(data)
运行代码时,我会在控制台中看到输出 但是我如何引用数据中的每个项目 例如名称,普通
当我尝试使用以下代码访问时,
console.log(data.studentData.Name)
我收到错误消息
console.log(data.studentData.Name)
^
TypeError: Cannot read property 'Name' of undefined
答案 0 :(得分:0)
data.studentData
是一个数组,因此您需要遍历每个值。
以forEach
为例:
data.studentData.forEach((individualStudentData) => {
console.log(individualStudentData.Name);
//Do your thing (:
});
或者:
for (let individualStudentData of data.studentData)
.map(() => { ... }
之类的功能答案 1 :(得分:0)
看起来像data.studentData实际上是一个JSON数组。因此,如果您想记录每个姓名,则需要
const data = require("./testdata.json");
data.studentData.forEach( student => console.log(student.Name));