JSON (JavaScript Object Notation) is a way to represent data through text. It exists as a String and it supports all the basic data types that are supported by a standard JavaScript object. As per Wikipedia, the definition goes –
Note – I am putting my JavaScript Developer study notes here.
There are two methods that I will be discussing in this post.
JSON.parse()
This method is used to deserialize or convert a JSON string into a JavaScript object. This is highly used while accessing the external API/server response. In the below example, I am converting a string to a JavaScript object using the parse method. You can use the dot (.) to access the individual items in the object.
Code:
constjsonString = `
{
“name”:”Sudipta Deb”,
“country”:”Canada”,
“favouriteCars”:[
“Honda”,”BMW”
],
“employed”:true
}
`;
constjsonObject = JSON.parse(jsonString);
console.log(jsonObject);
console.log(jsonObject.name);
Output:
{
name: ‘Sudipta Deb’,
country: ‘Canada’,
favouriteCars: [ ‘Honda’, ‘BMW’ ],
employed: true
}
Sudipta Deb
JSON.stringify()
This method is used to serialize or convert a JavaScript object into a JSON string. This is highly used before transferring data to an external API/server. In the below example, I am converting the above JavaScript object to a string using the stringify method.