Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Node.js Basics 2017 Building a Command Line Application Parsing JSON

How to access first element of JSON object array?

How to access first element of JSON object array?

{"symbols_requested":3,"symbols_returned":3,"data":[{"symbol":"AAPL","name":"Apple}]

I want to access name

Steven Parker

1 Answer

Steven Parker
Steven Parker
231,261 Points

:bell: Hi, I got alerted by your tag; but there's a lot of students (and occasionally instructors!) willing to help — next time try giving the whole community at least a day to answer and you can always tag someone(s) later.

This code appears to be a JavaScript object literal. It's JSON-compatible, but it's not in JSON format now. It also seems to have two errors:

  • a quote mark is missing after "Apple"
  • and closing is brace is missing at the very end

So if we fix those and format it to make it easier to read:

{"symbols_requested": 3,
  "symbols_returned": 3,
  "data": [ {"symbol": "AAPL",
             "name": "Apple"} ]
}

We can see that "name" is a property of an object that is inside the first element of an array named "data", which is itself inside the main object. So for example, if this object were being reference by a variable named "test", you could access the name as:

test.data[0].name