How to Implement localStorage in Html5 to store JSON data and read JSON data, html5json
LocalStorage is a method provided by HTML5 to implement local storage on the client, but the localStorage method can only store string data. Sometimes we need to store objects locally, such as JSON, how can localStorage store and read JSON data?
Idea: Since localStorage can only store string data, we can first convert the JSON object into a string and then store it using the localStorage method. When the JSON data needs to be used, read them first, and then convert them to JSON objects for use.
The Code is as follows:
Var jsonData = {'name': 'zhang san', 'age': 29}; // defines a JSON object var str_jsonData = JSON. stringify (jsonData); console. log (typeof (str_jsonData); // stringlocalStorage. setItem ('localdata', str_jsonData); // store string data to the local var getLocalData = localStorage. getItem ('localdata'); // reads the string data console. log (typeof (getLocalData); // stringvar jsonObj = JSON. parse (getLocalData); console. log (typeof (jsonObj); // objconsole. log (jsonObj. age); // 29
Extension:
Stringify () is used to parse a string from an object;
Parse () is used to parse json objects from a string.
The above section describes how to implement localStorage in Html5 to store JSON data and read JSON data. I hope it will help you. If you have any questions, please leave a message, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!