Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
220,450 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