Home > Article > Web Front-end > Detailed explanation of the implementation method of localStorage storing JSON data and reading JSON data in Html5
localStorage is a method provided by HTML5 to implement local storage on the client. However, the localStorage method can only store string data. Sometimes we need to store objects. To local, for example: JSON; So, how can localStorage realize the storage and reading of JSON data? Let’s explain the solution ideas through this article, let’s take a look
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; 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
The above is the detailed content of Detailed explanation of the implementation method of localStorage storing JSON data and reading JSON data in Html5. For more information, please follow other related articles on the PHP Chinese website!