How to Implement localStorage in Html5 to store JSON data and read JSON data, html5json

Source: Internet
Author: User

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!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.