Questions about Localstorage storing JSON objects

Source: Internet
Author: User

If you try to store object with Localstorage, you accidentally find out that it's not what you want, such as:

Stores an object and assigns the value of the Name property of the object to the P label.

Html:

< P > </ P >

Js:

var fruit={        name:' Apple ',        color:' red ',        taste:' sweet '    }    localstorage.myfruit=fruit;    Console.log (localstorage.myfruit);    document.getElementsByTagName (' P ') [0].innerhtml=localstorage.myfruit.name;

Results:

At this point you will find that the value of name cannot be taken out. So we need to do something extra when we access the object, as follows:

Js:

  

var fruit={
Name: ' Apple ',
Color: ' Red ',
Taste: ' Sweet '
}


Localstorage.myfruit=json.stringify (fruit); //Convert object type to String type store
Console.log (Localstorage.myfruit);

var obj=json.parse (localstorage.myfruit); //re-parses the string into a JSON object
document.getElementsByTagName (' P ') [0].innerhtml=obj.name;

Results:

Conclusion:

  When you use Localstorage for storage, you need to use the Json.stringify () method to convert an object to string and then store it.

You need to use the Json.parse () method to return a string to object when the value is taken.

Questions about Localstorage storing JSON objects

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.