JSON Parse

JSON Parse

A common use of JSON is exchanging data with a web server.

When receiving data from a web server, the data is always sent to your browser as a plain text string.


Using JSON.parse()

To convert this plain text string into a highly usable JavaScript object, use the JSON.parse() function.

Once parsed, you can access the data inside it exactly like a normal JavaScript object using dot notation.

If the string contains invalid syntax, the JSON.parse() method will crash your script entirely!


Parsing Dates

JSON does not allow real Date objects to be transferred.

If you need to include a date in JSON, you must write it as a string.

After parsing the data, you can convert that specific string back into a JavaScript Date object manually.

JSON.parse() Example:

// The server sends this text string
let serverText = '{"name":"John", "birth":"1990-12-14", "city":"New York"}';

// Convert the string into an object let obj = JSON.parse(serverText);

// Convert the birth string back into a real Date object obj.birth = new Date(obj.birth);

console.log(obj.name + " was born on " + obj.birth.getFullYear());


SEO and Error Handling

Always use a try...catch block when parsing JSON from an external, unpredictable API.

If the server sends a corrupted string, a crashed JavaScript file will severely break your website's user experience.

Stable, fast-loading applications are highly prioritized by search engine algorithms.


Exercise 1 of 1

?

Which native JavaScript function is used to convert a JSON text string into a JavaScript object?