如何将JSON数据存储和检索到本地存储? [英] How to store and retrieve JSON data into local storage?

查看:130
本文介绍了如何将JSON数据存储和检索到本地存储?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码:

var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
localStorage.setItem('added-items', JSON.stringify(string));

此代码将使用localStorage。

This code will use localStorage.

现在是获取存储数据的代码:

Here is now the code to get the stored data:

var retrievedObject = localStorage.getItem('added-items');

我现在的问题是,我如何获得数据项的大小?答案必须是2。

My problem now is, how can i get the size of the data items? answer must be 2.

如何获得Item1和Item2?

How can i get the "Item1" and "Item2"?

我试过 retrieveObject [0] [0] 但它无效。

以及如何在其上添加数据?
所以它将是

And how to add data on it? so it will be

{"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"Desc":"Item3"}]}

我可以使用 JSON.stringify

推荐答案

var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
localStorage.setItem('added-items', JSON.stringify(string));

stringify 表示,取 object 并将其演示文稿作为字符串返回。
你拥有的,已经是一个字符串,而不是一个JSON对象。

stringify means, take an object and return its presentation as a string. What you have, is already a string and not a JSON object.

相反的是 JSON.parse 接受字符串并将其转换为对象

The opposite is JSON.parse which takes a string and turns it into an object.

它们都与获取数组的大小无关。正确编写JavaScript代码时,您几乎不会使用 JSON.parse JSON.stringify 。仅当明确需要序列化时。

Neither of them have anything to do with getting the size of an array. When properly coding JavaScript you almost never use JSON.parse or JSON.stringify. Only if serialization is explicitly wanted.

使用 length 获取数组的大小:

var obj = {"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"Desc":"Item3"}]}
console.debug(obj.items.length);

这篇关于如何将JSON数据存储和检索到本地存储?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆