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 -
JSON (JavaScript Object Notation, pronounced /ˈdʒeɪsən/; also /ˈdʒeɪˌsɒn/) is an open standard file format, and data interchange format, that uses human-readable text to store and transmit data objects consisting of attribute–value pairs and array data types (or any other serializable value).
Reference: https://en.wikipedia.org/wiki/JSON
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:
const jsonString = `
{
"name":"Sudipta Deb",
"country":"Canada",
"favouriteCars":[
"Honda","BMW"
],
"employed":true
}
`;
const jsonObject = 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.
Code:
const jsonString = `
{
"name":"Sudipta Deb",
"country":"Canada",
"favouriteCars":[
"Honda","BMW"
],
"employed":true
}
`;
const jsonObject = JSON.parse(jsonString);
const jsonAsSerialized = JSON.stringify(jsonObject);
console.log(jsonAsSerialized);
Output:
{"name":"Sudipta Deb","country":"Canada","favouriteCars":["Honda","BMW"],"employed":true}
Here is the youtube video
0 Comments