JSON.parse() and JSON.stringify() explained

    Oct 28, 2019       by Pankaj Kumar
json-parse-and-json-stringify.jpg

The different web browsers available today provide some standard methods, properties.

The JSON object, available in all modern browsers, has two very useful methods to deal with JSON-formatted content: parse and stringify. JSON.parse() takes a JSON string as an argument and transforms it into a JavaScript object. JSON.stringify() takes a JavaScript object as an argument and transforms it into a JSON string. If you have worked on the API integration/creation task earlier then you must have come across this method. Understanding of these two methods are necessary because most of the API developed today in REST format and JSON is preferred with REST API.

 

JSON.parse()

This method parses the string text as JSON, optionally transform the produced value and its properties and return the value. Normally we pass single string argument in to convert it into JSON format but it can also take the second argument for a reviver function that can transform the object values before they are returned.

Syntax:

JSON.parse(text[, reviver])

 

Example:

 
let a ='{ "name":"John", "age":30, "city":"New York"}';
let b = JSON.parse(a);
console.log('data type of b:'+typeof(b));
console.log(b);
 
// Output:
/*"data type of b:object"
[object Object] {
age: 30,
city: "New York",
name: "John"
}
*/
 

 

JSON.stringify()

Normally while using this method we pass a single argument in it, But this method can take two additional arguments, first a replacer function and second a String/Number to use as a space in the returned string value. The replacer(function) can be used to filter values, This way if some don't want some specific string then it can be removed from the returned string

Syntax:

JSON.stringify(value[, replacer[, space]])

 

Example:

 
let obj = { name: "John", age: 30, city: "New York" };
let myJSON = JSON.stringify(obj);
 
console.log("type of myJSON: "+typeof(myJSON));
console.log(myJSON);
// Output:
/*
"type of myJSON: string"
"{"name":"John","age":30,"city":"New York"}"
*/
 

 

Let me know your thoughts over email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share it with your friends.

Thanks!


WHAT'S NEW

Find other similar Articles here: