简体   繁体   English

创建和读取 JSON 文件

[英]Create and Read JSON file

  1. I created a JSON file as follows我创建了一个 JSON 文件如下
{
    
"fooditems" : [
        {
            "name": "pizza",
        "type": "fastfood",
        "price": 10
        },
        {
            "name": "apple",
        "type": "fruit",
        "price": 1
        }
    ]

}
  1. created a JS file to read the JSON file创建了一个 JS 文件来读取 JSON 文件
const data = require("./data.json");
    
data1 = JSON.parse(data);

data1.foodData.forEach( foodItem => console.log(foodItem));    
  1. When I run the JS, I get error for the json file当我运行 JS 时,我收到 json 文件的错误

Syntax error: Unexpected token o in json at position 1 at JSON.parse语法错误:JSON.parse 位置 1 处的 json 中出现意外标记 o

You don't need to parse data since it's already and object.您不需要解析data因为它已经是对象了。 The following should work.以下应该工作。

const data = require("./data.json");
data.fooditems.forEach( foodItem => console.log(foodItem));  

Note foodData was change to fooditems based on the contents of the data.json file.注意foodData已根据 data.json 文件的内容更改为fooditems

Your initial data JSON contains "fooditems", but in the JS file you are trying to process the "foodData".您的初始数据 JSON 包含“fooditems”,但在 JS 文件中您正尝试处理“foodData”。 Change the "foodData" to "fooditems" and it should work.将“foodData”更改为“fooditems”,它应该可以工作。

I think that you are trying to access invalid object key in your JS file on the last line.我认为您正在尝试访问最后一行 JS 文件中的无效对象键。

Instead of data1.foodData put data1.fooditems而不是data1.foodDatadata1.fooditems

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM