How to access data in json using nodejs

I am trying to access data in a json file using nodeJS

When I run this, I get the error: TypeError: Cannot read property "zip code" undefined. Any suggestions?

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

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

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

Run codeHide result


+3


source to share


3 answers


Try to access the following data:

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

      



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

+4


source


In your json, pages

and results

are arrays. You need to access them using the index. Also, you have a typo in the title.

Try the following:



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

      

+1


source


This will give you the correct answer.

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

      

0


source







All Articles