简体   繁体   中英

Create and Read JSON file

  1. I created a JSON file as follows
{
    
"fooditems" : [
        {
            "name": "pizza",
        "type": "fastfood",
        "price": 10
        },
        {
            "name": "apple",
        "type": "fruit",
        "price": 1
        }
    ]

}
  1. created a JS file to read the JSON file
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

Syntax error: Unexpected token o in json at position 1 at JSON.parse

You don't need to parse data since it's already and object. 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.

Your initial data JSON contains "fooditems", but in the JS file you are trying to process the "foodData". Change the "foodData" to "fooditems" and it should work.

I think that you are trying to access invalid object key in your JS file on the last line.

Instead of data1.foodData put data1.fooditems

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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