JSON.parse()


JSON is often used to send and receive data between a website and a server.

When you get information from a web server, it's always in the form of text.

To change data into a JavaScript object, use JSON.parse().


Example - Parsing JSON

Let's say we got this message from a website server:

'{"name":"John", "age":30, "city":"New York"}'

Use the JavaScript function JSON.parse() for transforming text into a JavaScript object.

const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}');

Ensure that the text follows JSON format; otherwise, it may result in a syntax error.

Include the JavaScript object on your webpage.


Array as JSON

If you use JSON.parse() on JSON that comes from an array, it gives back a JavaScript array, not a JavaScript object.


Exceptions

Parsing Dates

JSON does not permit the use of date objects.

If you want to add a date, just write it as a group of letters.

You can change it back to a date object afterward.

Alternatively, you have the option to utilize the second parameter in the JSON.parse() function, known as reviver.

The reviver parameter is a function that examines each property before providing the final value.

Parsing Functions

In JSON, you can't use functions.

If you want to add a function, type it out as a string.

You can change it back into a function afterwards.

It's better not to use functions in JSON because they lose their scope. If you do use them, you might need to use eval() to turn them back into functions.