Javascript JSON Parse and Stringify with Examples
1 minsJSON stands for Javascript Object Notation. It is a lightweight language-independent data interchange format.
A common use of JSON is to exchange data to/from a web server. When sending data to a server, you need to send it as a JSON string. And when you’re receiving JSON data from a server, you would need to parse it to a Javascript object.
Javascript has two functions namely JSON.stringify()
and JSON.parse()
to convert a Javascript object to json string and vice versa. Let’s look at how these functions work:
JSON.stringify(): Convert Javascript object to JSON
You can use the JSON.stringify()
function to convert a Javascript object to json string. Here is how you can use this function -
var user = {
name: "Rajeev Singh",
age: 26,
address: {
city: "Bangalore",
State: "Karnataka",
Country: "India"
},
hobbies: ["Coding", "Travelling", "Photography"]
};
var jsonData = JSON.stringify(user);
console.log(jsonData);
# Output
{"name":"Rajeev Singh","age":26,"address":{"city":"Bangalore","State":"Karnataka","Country":"India"},"hobbies":["Coding","Travelling","Photography"]}
JSON.parse(): Parse a JSON string
You can use the JSON.parse() function to parse a json string to a Javascript object. Here is how you can use this function -
var jsonData = `
{
"name": "Sachin Tendulkar",
"age": 26,
"address": {
"city": "Mumbai",
"State": "Maharastra",
"Country": "India"
},
"hobbies": [
"Cricket",
"Badminton"
]
}
`;
var user = JSON.parse(jsonData);
console.log(user);
# Output
{
name: "Sachin Tendulkar",
age: 26,
address: { city: "Mumbai", State: "Maharastra", Country: "India" },
hobbies: [ "Cricket", "Badminton" ]
}