Resolving Localstorage storage JSON object storage format problems in HTML5

Source: Internet
Author: User
Tags json object object string format

Localstorage.setitem (att) automatically stores att as a string, such as:

The code is as follows Copy Code

var arr=[1,2,3];
Localstorage.setitem ("temp", arr);
typeof Localstorage.getitem ("temp"); Returns a string
Localstorage.getitem ("temp"); returns 1,2,3

It is worth noting, however, that Localstorage.setitem () does not automatically turn the JSON object into a string, such as:

The code is as follows Copy Code

var obj={"A": 1, "B": 2];
Localstorage.setitem ("Temp2", obj);
typeof Localstorage.getitem ("Temp2"), also returns a string
Localstorage.getitem ("temp"), but returns [Object Object]

The correct way to store the JSON object using Localstorage.setitem () is to convert the JSON object to a string using the Json.stringify () method before storage, such as:

The code is as follows Copy Code

var obj={"A": 1, "B": 2};
Obj=json.stringify (obj);
Localstorage.setitem ("Temp2", obj);
typeof Localstorage.getitem ("Temp2"); return string
Localstorage.getitem ("Temp2"); return string format: {"A": 1, "B": 2}

To manipulate the JSON object later, it is natural to convert the previously stored JSON string into a JSON object and then manipulate it, such as:

The code is as follows Copy Code

Obj=json.parse (Localstorage.getitem ("Temp2"));

After the operation, storage information, remember to convert the format: obj=json.stringify (obj);

In addition: Localstorage.getitem (ATT), if ATT is not defined, returns a null value instead of the undefined

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.