JSON.parse() and JSON.stringify() featured image

A Tutorial on Working with JSON.parse() and JSON.stringify()

JSON stands for JavaScript Object Notation. It is used to describe JavaScript objects. It is a data-sharing format that specifies data values using key-value pairs. The JSON object is supported across all major browsers. This tutorial requires that you are familiar with JavaScript and working with the JSON object. To get familiar with JSON, you can take a look at our overview of the JSON data sharing format. You can also check out how to work with JSON in JavaScript.

The JSON format is also used to transmit data across the network. For this purpose, data needs to be serialized and deserialized. When the data is in the JSON format it is converted into a string using the stringify method. To convert the data back to the object format for manipulation, the parse method is used. This tutorial is going to go over the steps of using JSON.parse() and JSON.stringify(). Let’s begin!

JSON.parse()

This method is used to convert a JSON string into a JSON object so that it can be manipulated programmatically. The string being passed needs to be a valid JSON string otherwise an exception will be thrown. This string can be received from any web service or remote application.

This method accepts two parameters: a string and a callback function which can be used to manipulate the string before converting it into an object. Suppose we are receiving a message from a web service indicating the status of the action, message, and status code. Below is a simple example of how a string can be converted into an object.

Code:

Output:

A common problem is when trailing commas are added to the string, so JSON.parse() throws an error if the string passed to it has trailing commas. If you need to manipulate the values, you can pass in the callbackfunction as a second argument.

Code:

Output:

JSON.stringify()

The stringify method does exactly the opposite of the parse method. Here, the JSON object is passed, and the return value is a string. This string can be passed to some other remote web service, for example, and then parsed again into a JSON object for manipulation.

Code:

Output:

The stringify method can take two arguments: replacerand spacer methods. The replacer method can be used to replace or exclude any values in the string.

Code:

Output:

When the spacer argument is provided, each element of an array or object is placed on its line and indented to indicate its depth in the hierarchy of the objects and arrays. Below is a simple code snippet illustrating this.

Code:

Output:

Conclusion

In this tutorial, we looked at two helpful methods to work with JSON-formatted content. JSON objects are everywhere and when building modern applications using JavaScript these methods are very useful. To learn more, check out the following tutorials on our blog:

Happy Computing!