3

I'm trying to access data within a json file using nodeJS

When I run this I get the error: TypeError: Cannot read property 'postcode' of undefined. Any Suggestions?

{
    "apiName": "Restaurants",
    "pages": [
        {
            "pageUrl": "https://url",
            "results": [
                {
                    "address": "3F Belvedere Road Coutry Hall, London, SE17GQ",
                    "phone": "+442076339309",
                    "name": "Name",
                    "postcode": "SE17GQ"
                }
            ]
        }    
    ]
}

var myData = require('./jsonFile.json');

console.log(myData.pages.result.postcode);

0

3 Answers 3

4

Try to access data as below:

console.log(myData.pages[0].results[0].postcode);

The value in the bracket is the index of element to access.
Its the common singular/plural trap, I fall for it all the time.

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

Comments

1

In your json, pages & results are arrays. You need to access these with an index. Also, you have a typo in the name.

Try this:

console.log(myData.pages[0].results[0].postcode);

Comments

0

This will gave you correct answer.

console.log(myData.pages[0].results[0].postcode);

Comments

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.