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和stringify 。 在上一篇文章中,我们学习了在JS中使用本地存储的知识,并了解了它可以与键值对一起使用,并且只能将它们作为字符串接受。 现在我们可以使用一个对象保存多个信息,例如,这个巨大的对象包含几个元素,包括数组和对象本身。
![JSON - parse and stringify](https://www.includehelp.com/code-snippets/Images/json-parse-and-stringify.jpg)
Using an object in place of the mere string. So how can we add an object, then we will use a JSON stringify.
使用对象代替单纯的字符串。 那么我们如何添加对象,然后我们将使用JSON字符串化。
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?
这里有一个对象Student , 名称为Minato和34 , isActive为true 。 现在,我们将尝试看看如何将其转换为字符串并返回对象?
To convert OBJECT to STRING:
要将对象转换为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.
要将对象转换为字符串,请使用JSON.stringify(objectName) ,此函数将返回该对象的字符串。 现在我们可以在localStorage中使用该对象。
To convert STRING to OBJECT:
要将STRING转换为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.
现在,当我们将Object转换为字符串,然后再检索该键-值对时,我们可能无法使用该STRING版本的Object,因此我们需要做的是将其更改回一个对象,并可以使用使用JSON.parse(StringObject)将返回对象。
翻译自: https://www.includehelp.com/code-snippets/json-parse-and-stringify.aspx