JavaScript Node.js Basics Handling Errors in Node Handling Parsing and Status Code Errors

Matthew Leroe
Matthew Leroe
9,440 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,770 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.

Matthew Leroe
Matthew Leroe
9,440 Points

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

Cooper Runstein
Cooper Runstein
11,770 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