Home
Aptitude
Categories


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.

JSON - parse and stringify

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.