0
  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

Barbaros Özhan
  • 59,113
  • 10
  • 31
  • 55
Sudhir Jangam
  • 646
  • 2
  • 13
  • 20
  • log the contents of `data` to the console before you try to parse it and check what it really looks like. Usually this error is because the data is in fact already an object (rather than a string), and therefore doesn't need parsing. `require` already treats it as an object. – ADyson Sep 24 '20 at 21:22
  • Does this answer your question? [SyntaxError: Unexpected token o in JSON at position 1](https://stackoverflow.com/questions/38380462/syntaxerror-unexpected-token-o-in-json-at-position-1) – ADyson Sep 24 '20 at 21:23

3 Answers3

2

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.

Shane Richards
  • 341
  • 1
  • 2
  • 9
0

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.

Diceros
  • 83
  • 6
0

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

Joundill
  • 6,828
  • 12
  • 36
  • 50