Home »
JSON
JSON - parse and stringify
In this article, we are going to learn about JSON - Parse and Stringify.
Submitted by Himanshu Bhatt, on October 09, 2018
We learned how to add or retrieve key-value from local storage and using JSON parse and stringify. In the previous article, we learned to work with local storage in JS and learned that it works with the key-value pair and accept them as string only. Now we can use an object to save multiple information, for example, this gigantic object holds several elements including arrays and objects itself.
Using an object in place of the mere string. So how can we add an object, then we will use a JSON stringify.
const student = {
name: 'Minato',
age :34,
isActive:true,
}
We have here an object Student having name Minato and 34 and isActive as true. Now we will try to see how we will convert it to a string and back to object?
To convert OBJECT to STRING:
const studentObjToString = JSON.stringify(student) //stringify
console.log(typeof studentObjToString);
OUTPUT: string
To convert an object to a string use JSON.stringify(objectName) and this function will return a string of that object. Now we can use the object in localStorage.
To convert STRING to OBJECT:
jsonObj = JSON.parse(studentObjToString)
console.log(typeof jsonObj);
Output: object
Now when we convert Object into a string and later if we retrieve that key-value pair we may not able to use that STRING version of our Object so what we need to do is, change it back to an object and we can do it with using JSON.parse(StringObject) which will return the object.