Reputation: 51
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
Reputation: 441
This will gave you correct answer.
console.log(myData.pages[0].results[0].postcode);
Upvotes: 0
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
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