In this article, you’ll learn what is JSON.Stringify()
and JSON.Parse()
and how to use those functions. The JSON object has two methods to deal with JSON-formatted content: JSON.Stringify()
and JSON.Parse()
.
Here we learn the about JSON.Stringify()
and JSON.Parse()
.
JSON.Stringify()
takes a JavaScript object and converts it into a JSON string. It serializes a JavaScript object into a JSON string.
let userObject = {
name: "Sameer",
email: "contact@tutorialsrack.com",
plan: "Premium"
};
let userString = JSON.stringify(userObject);
console.log(userString);
//Output ==> "{\"name\":\"Sameer\",\"email\":\"contact@tutorialsrack.com\",\"plan\":\"Premium\"}"
The JSON.stringify()
method takes two additional arguments, where the first argument is a replacer function and the second argument is a String
or Number
value to use as a space in the returned string:
let userObject = {
name: "Sameer",
email: "contact@tutorialsrack.com",
plan: "Premium"
};
function replacer(key, value) {
if (key === 'email') {
return undefined;
}
return value;
}
let userStrReplacer = JSON.stringify(userObject, replacer);
console.log(userStrReplacer);
//Output ==> "{\"name\":\"Sameer\",\"plan\":\"Premium\"}"
The email
key-value pair has been removed from the object using the replacer function.
Here is another example with a space argument passed in. Let's take a look at an example:
let userObject = {
name: "Sameer",
email: "contact@tutorialsrack.com",
plan: "Premium"
};
let userStrSpace = JSON.stringify(userObject, null, '...');
console.log(userStrSpace);
"{
...\"name\": \"Sameer\",
...\"email\": \"contact@tutorialsrack.com\",
...\"plan\": \"Premium\"
}"
The indentation has been replaced with ...
JSON.Stringify()
takes a JSON string and converts it into a JavaScript object. It deserializes a JSON string into a JavaScript object.
let userStr = '{\"name\":\"Sameer\",\"email\":\"contact@tutorialsrack.com\",\"plan\":\"Premium\"}';
let userObj = JSON.parse(userStr);
console.log(userObj);
[object Object] {
email: "contact@tutorialsrack.com",
name: "Sameer",
plan: "Premium"
}
Note: JSON.parse()
throws if the string passed to it has trailing commas.
JSON.parse()
can take a function as a second argument that can transform the object values before they are returned.
Here is the example, the object’s values are transformed to uppercase in the returned object of the parse method, let’s take an example:
let userStr = '{\"name\":\"Sameer\",\"email\":\"contact@tutorialsrack.com\",\"plan\":\"Premium\"}';
let userObj = JSON.parse(userStr, (key, value) => {
if (typeof value === 'string') {
return value.toUpperCase();
}
return value;
});
console.log(userObj);
[object Object] {
email: "CONTACT@TUTORIALSRACK.COM",
name: "SAMEER",
plan: "PREMIUM"
}
I hope this article will help you to understand what is JSON.Stringify() and JSON.Parse() and how to use those functions.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments