2

I would like to add names to multiple JSON objects at the same time.

I tried this:

let jdata = fs.readFileSync('participants.json');
let json = JSON.parse(jdata);
jury = ["jury1", "jury2"];
for(i=1; i<3; i++){
    data = json.jury[i];
    console.log(data);
}

My JSON file: { "jury1": [ "name1", "name2", "name3" ], "jury2": [ "name1", "name2", "name3" ] } This gives me an error:

            data = json.jurys[i];
                              ^

TypeError: Cannot read property '1' of undefined

I haven't used JSON before and i'm not sure how to get all of the values from these objects. Could someone tell me what i'm doing wrong? Thanks for your time and help already!

2
  • Use square brackets like this data = json[jury[i]]; Commented Oct 19, 2017 at 10:17
  • I know whats wrong now @gurvinder372 explained it! Commented Oct 19, 2017 at 10:24

1 Answer 1

3

TypeError: Cannot read property '1' of undefined

Your json doesn't have a jury attribute.

So, json.jury returns undefined and hence your error.

Make it

for(i=0; i<jury.length; i++)
{
    data = json[jury[i]]; //notice the change here
    console.log(data);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so so much, I edited the loop so it gets both objects, but it works now! Can't thank you enough!

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.