Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
读取具有不同数据类型的JSON文件_Json - Fatal编程技术网

读取具有不同数据类型的JSON文件

读取具有不同数据类型的JSON文件,json,Json,我试图读取包含以下数据的JSON文件 "{\"studentData\":[{\"Name\":\"Graham\",\"aggregate\":\"86\",\"regular\":\"true\",\"percentages\":[{\"sub1\":\"69\",\"sub

我试图读取包含以下数据的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)
当我运行代码时,我会在控制台中看到输出 但是我如何引用数据中的每一项呢 e、 g.姓名,普通

当我尝试使用以下代码访问时

   console.log(data.studentData.Name)
我犯了一个错误

   console.log(data.studentData.Name)
                                 ^

TypeError: Cannot read property 'Name' of undefined

data.studentData
是一个数组,因此需要循环遍历每个值

使用forEach的
forEach
例如:

data.studentData.forEach((individualStudentData)=>{
log(individualStudentData.Name);
//做你的事(:
});
或:

  • for(让单个studentData为data.studentData)
  • 类似于
    .map(()=>{…}
  • 等等;)

看起来像data.studentData实际上是一个JSON数组。因此,如果您想记录每个名称,您需要这样做

const data = require("./testdata.json");
data.studentData.forEach( student => console.log(student.Name));

您必须循环使用它。有多个名称,但您试图一次获取所有名称。尝试过,但不起作用,尝试使用~~~控制台.log(data.studentData);~~~它给出了未定义的名称。好的,您尝试过删除开始和结束<代码>“,以及JSON中的反斜杠“\”?目前您的JSON无效:)您可以随时检查此处,以供参考。如果您从web查询中获得此JSON,您可以手动处理它,如
。在字符串上替换('\','')
,并使用
JSON.parse([string here])
解析它的工作原理,我用现有数据添加了JSON.parse,然后使用了foreach,谢谢你的帮助我得到了错误数据。studentData.foreach(student=>console.log(student.Name));^TypeError:无法读取未定义数据的属性“forEach”,请尝试改用数据[“studentData”]。如果这仍然不起作用,那么可能存在解析问题。