Guven8
Guven8

Reputation: 51

How to access data within json using nodejs

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

Upvotes: 3

Views: 108

Answers (3)

Viddesh
Viddesh

Reputation: 441

This will gave you correct answer.

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

Upvotes: 0

Amit
Amit

Reputation: 46323

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

Upvotes: 1

Paul Marrington
Paul Marrington

Reputation: 557

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.

Upvotes: 4

Related Questions