The JSON object has two useful methods which are used to parse JSON data from string or convert JavaScript object into string.

The JSON.stringify() method converts a JavaScript object or value into a JSON string whereas JSON.parse() method parses a JSON string into a JavaScript object.

If you have worked on AJAX’s XMLHttpRequest(), then you would have noticed that the response we get is basically a String. So to use that response data, you have to parse it to JavaScript object and there comes this JSON.parse() as rescue.

Let’s take a closer look on each of the methods.


Stringify() with JavaScript objects
const obj = {
    name: 'Amitav',
    age: 24,
    designation: 'Software Engineer'
const objString = JSON.stringify(obj);
// "{"name":"Amitav","age":24,"designation":"Software Engineer"}"
Stringify() with JavaScript Arrays
const arr = [1, 2, 'hello','world'];
const arrString = JSON.stringify(arr);
// "[1,2,"hello","world"]"

Some more examples:

JSON.stringify(45); // "45"
JSON.stringify(true); // "true"
JSON.stringify({a:1, b:undefined, c:null}); 
// "{"a":1,"c":null}" -> undefined value will be removed

JSON.stringify() can accept two additional arguments, one is replacer and other is spacer. A replacer can either be a function or an array.

#javascript #programming #developer

Difference Between JSON.parse() and JSON.stringify()
38.85 GEEK