'Can't read my JSON file using require method in JS
I'm trying to loop through JSON data that I'm pulling from a file. I'm using the require function to get the JSON file but it keeps telling me there is an unexpected '{' token? positions on IDE and console are a little off but I'm pretty sure it's the second objects opening { -position 44-
Any suggestions?
myData.json
{
"colour" : "blue",
"cm" : 2
}
{
"colour" : "red",
"cm" : 5
}
index.js
const fileContents = require("./myData.json");
Solution 1:[1]
Because the JSON is invalid. Your JSON file needs to define one entity, where currently you're defining two. Even if the code could read the data, there's no logical way to indicate which of those two objects you want to refer to.
It looks like you meant to put them in an array:
[
{
"colour" : "blue",
"cm" : 2
},
{
"colour" : "red",
"cm" : 5
}
]
Then you can import the whole array, and refer to elements of the array for each object.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | David |
