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

Michael M.
11.2k11 gold badges22 silver badges46 bronze badges
asked Aug 5, 2015 at 22:08
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.

MaxZoom
7,7635 gold badges30 silver badges45 bronze badges
answered Aug 5, 2015 at 22:12
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);
answered Aug 5, 2015 at 22:13

Comments

0

This will gave you correct answer.

console.log(myData.pages[0].results[0].postcode);
answered Aug 6, 2015 at 7:44

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.