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);
Michael M.
11.2k11 gold badges22 silver badges46 bronze badges
3 Answers 3
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.
MaxZoom
7,7635 gold badges30 silver badges45 bronze badges
answered Aug 5, 2015 at 22:12
Paul Marrington
5572 silver badges7 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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);
answered Aug 5, 2015 at 22:13
Amit
46.5k9 gold badges84 silver badges114 bronze badges
Comments
This will gave you correct answer.
console.log(myData.pages[0].results[0].postcode);
answered Aug 6, 2015 at 7:44
Viddesh
4411 gold badge5 silver badges19 bronze badges
Comments
lang-js