0

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");
1

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah thank you :D I thought if I used the [ ] it might not be a proper JSON onject after reading someone elses similar quetion on here; but I suppose they weren't technically using a JSON file were as I am. Thanks again :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.