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 Handling Errors in Node Handling Parsing and Status Code Errors

Routine Poutine
Routine Poutine
26,050 Points

Do strings ever contain objects in real life? Can you JSON.parse() an array?

Is the code here just for demonstration, or would it ever be used in real life?

personString = '{name: lauren}';

I've never seen braces inside of a string before, only inside of brackets, such as an array of objects:

[{name: lauren}].

Could you parse an array of objects?

2 Answers

Cooper Runstein
Cooper Runstein
11,850 Points

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

JSON is always treated as a string, but remember that json is a data format, not Javascript in the typical sense.

Routine Poutine
Routine Poutine
26,050 Points

How about prior to JSON.parse()? I've never seen a string of objects parsed into JSON before.

Cooper Runstein
Cooper Runstein
11,850 Points

I think you're misunderstanding JSON.parse(), if I contact and API, request some data, and get a response in JSON, I'm going to pull it in as a string. It would look kinda like:

"{"data": [1,2,3]}"

JSON.parse() is used to take that string of JSON and turn it into a JavaScript Object. You're not going to use parse to send a JS object into JSON, you'd use JSON.stringify() for that: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify