Home  >  Article  >  Web Front-end  >  How to implement localStorage storage and reading JSON

How to implement localStorage storage and reading JSON

php中世界最好的语言
php中世界最好的语言Original
2018-03-26 14:24:521607browse

This time I will show you how to read JSON from localStorage storage. What are the precautions for reading JSON from localStorage storage? The following is a practical case, let's take a look.

localStorage is a method provided by HTML5 to implement

local storage on the client side, but the localStorage method can only store string data. Sometimes we need to store ObjectTo local, for example: JSON; then, how can localStorage realize the storage and reading of 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 we need to use these JSON data, read them first Take it out and then convert it into a JSON object for use.

The specific code is as follows:

var jsonData = {'name': '张三', 'age': 29}; // 定义一个JSON对象
var str_jsonData = JSON.stringify(jsonData);
console.log(typeof(str_jsonData)); // string
localStorage.setItem('localData', str_jsonData); // 存储字符串数据到本地
var getLocalData = localStorage.getItem('localData'); // 读取字符串数据
console.log(typeof(getLocalData)); // string
var jsonObj = JSON.parse(getLocalData);
console.log(typeof(jsonObj)); // obj
console.log(jsonObj.age); // 29

Extension:

stringify() is used to parse a string from an object;

parse() is used to parse a string from an object Parse a json object from a string.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of H5 storage method


##postMessage implements cross-domain and cross-window messaging

The above is the detailed content of How to implement localStorage storage and reading JSON. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn