1. Using JSON.parse()
Passing a function – You can also pass a function as second (optional) argument to JSON.parse() function to perform some task on each JSON values. Here is an example to which a function transform all string values to uppercase in the returned object of the parse method:
We assume, this helps you to understand the uses of JSON.parse() method. Next, learn another method JSON.stringify() to perform the reverse of above.
2. Using JSON.stringify()
Here is a simple example of JSON.stringify() method:
You can also pass two additional arguments, One is the replacer function and the second can be the space value to format the output.
Using replacer function – A replacer function is used to filter the output values. For example, You can create a function and pass it as argument. This function will return any string value as undefined.
Using array as replacer – You can also pass an array containing some key names as replacer. Here the stringify() function will only return the matching key-pare values which keys are sent as replacer.
For example, we send id and name in an array as replacer function. In this case only those values are return as JS object and discarded any other values.
Passing space argument – You can also pass the space value as a third optional argument. This helps to make output in more readable format.
In this tutorial, you have learened the uses of the JSON.parse() and JSON.stringify() methods.