Difference between JSON.parse() and JSON.stringify()

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

The stringify() method converts a JavaScript object or value into a JSON string whereas the 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 a JavaScript object, and there we can use this parse().

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

JSON.stringify()

Stringify() with JavaScript objects

const obj = {
    name: 'Amitav',
    age: 24,
    designation: 'Software Engineer'
}

const objString = JSON.stringify(obj);

console.log(objString); 
// "{"name":"Amitav","age":24,"designation":"Software Engineer"}"

Stringify() with JavaScript Arrays

const arr = [1, 2, 'hello','world'];

const arrString = JSON.stringify(arr);

console.log(arrString); 
// "[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

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

Replacer as a function

The replacer function executes once for all the properties of the object.

const employee = {
    name: 'Amitav',
    id: '10113',
    address: {
        city: 'Bangalore',
        state: 'Karnataka'
    }
}

JSON.stringify(employee, (key, value) => {
  if(key === 'address') {
      return 'City: ' + value.city + ', State: ' + value.state;
  }
  return value;
});
// returns "{"name":"Amitav","id":"10113","address":"City: Bangalore, State: Karnataka"}"

Replacer as an Array

If the properties of the object are present in the replacer Array, then only those properties with their values will be returned after stringify().

const employee = {
    name: 'Amitav',
    id: '10113',
    address: {
        city: 'Bangalore',
        state: 'Karnataka'
    }
}

JSON.stringify(employee, ["name", 'id']);
// returns "{"name":"Amitav", "id":"10113"}"

The space argument

The space argument may be used to control spacing in the final string.

If the spacer is a number, it adds spaces equal to that number before every key and if the spacer is a string value, it will add that string value before every key.

Let’s take some examples.

JSON.stringify({a:232, b: 521}, null, "->");
// "{->"a":"232",->"b":"521"}"

JSON.stringify({a:232, b: 521}, null, 5);
/* 
 "{
    "a": 45,
    "b": 22
 }" 
*/

JSON.parse()

Parsing JSON

const objString = '{"name":"Amitav","age":24,"designation":"Software Engineer" }';

const obj = JSON.parse(objString );

console.log(obj); 
// {name:"Amitav",age:24,designation:"Software Engineer"}

If the string data is not in JSON format, the parse() method will throw an error.

JSON.parse("Hello World");
// throws SyntaxError

JSON.parse('{"hello", "World"}');
// throws SyntaxError

There should not be any single quote(‘) present inside the string data.

JSON.parse('{"name":'Amitav'}')
// throws SyntaxError

The Date objects are not allowed in JSON. If we stringify a Date object and then parse it, then it will no longer be a Date object, instead, it will be converted into a string formatted date.

const date = new Date();

console.log(date.toDateString());
// "Fri Apr 24 2020"

const transformedDate = JSON.parse(JSON.stringify(date));

console.log(transformedDate);
// "2020-04-24T15:48:23.474Z"

console.log(transformedDate.toDateString());
// throws TypeError

Parsing Array JSON

const arrString = '[1, 2, "Hello", "World"]';

const arr = JSON.parse(arrString);

console.log(arr); 
// [1, 2, "Hello", "World"]

Trailing commas are not valid in JSON.

JSON.parse('[1, 2, 3,]')
// throws SyntaxError

Some more Examples:

JSON.parse('true'); // true

JSON.parse('null'); // null 

JSON.parse('8.45'); // 8.45

The parse() method has a second optional parameter which is a function called reviver. This reviver function checks every property before parsing it.

const employee = {
    name: 'Amitav',
    id: 10113,
    address: {
        city: 'Bangalore',
        state: 'Karnataka'
    }
}

const empString = JSON.stringify(employee);

JSON.parse(empString, (key, value) => {
    if(key === 'address') {
        return 'City: ' + value.city + ', State: ' + value.state;
    }
    return value;
})
// returns {name:"Amitav", id:10113, address: "City: Bangalore, State: Karnataka"}

Hope you have got a clear idea about the stringify() and the parse() methods of JSON and their different use cases.

Leave a Reply

Your email address will not be published. Required fields are marked *