Javascript 如何将 JSON 数据存储和检索到本地存储中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34493531/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:25:49  来源:igfitidea点击:

How to store and retrieve JSON data into local storage?

javascriptjsonlocal-storage

提问by JMA

I have this code:

我有这个代码:

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

This code will use localStorage.

此代码将使用 localStorage。

Here is now the code to get the stored data:

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

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

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

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

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

我怎样才能得到“Item1”和“Item2”?

I tried retrievedObject[0][0]but it is not working.

我试过了,retrievedObject[0][0]但它不起作用。

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

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

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

Can I use JSON.stringify?

我可以使用JSON.stringify吗?

回答by Daniel W.

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

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

stringify意味着,采用 anobject并将其表示形式作为string. 你所拥有的已经是一个字符串而不是一个 JSON 对象。

The opposite is JSON.parsewhich takes a stringand turns it into an object.

相反的是JSON.parse将 astring变成 a object

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

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

Use lengthfor the size of the array:

使用length该数组的大小:

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

回答by JMA

// THIS IS ALREADY STRINGIFIED
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';

// DO NOT STRINGIFY AGAIN WHEN WRITING TO LOCAL STORAGE
localStorage.setItem('added-items', string);

// READ STRING FROM LOCAL STORAGE
var retrievedObject = localStorage.getItem('added-items');

// CONVERT STRING TO REGULAR JS OBJECT
var parsedObject = JSON.parse(retrievedObject);

// ACCESS DATA
console.log(parsedObject.items[0].Desc);

回答by zack

To bring clarity to future people that may stumble across this question and found the accepted answer to not be everything you hoped and dreamed for:

为了让未来的人们清楚地了解这个问题,并发现公认的答案并非您所希望和梦想的一切:

I've extended the question so that the user may either want to input a stringor JSONinto localStorage.

我已经扩展了这个问题,以便用户可能想要输入 astringJSONinto localStorage

Included are two functions, AddToLocalStorage(data)and GetFromLocalStorage(key).

包括两个函数,AddToLocalStorage(data)GetFromLocalStorage(key)

With AddToLocalStorage(data), if your input is not a string(such as JSON), then it will be converted into one.

使用AddToLocalStorage(data),如果您的输入不是 a string(例如JSON),那么它将被转换为 1。

GetFromLocalStorage(key)retrieves the data from localStorageof said key

GetFromLocalStorage(key)localStorage所述检索数据key

The end of the script shows an example of how to examine and alter the data within JSON. Because it is a combination of objects and array, one must use a combination of .and []where they are applicable.

脚本的末尾显示了如何检查和更改 JSON 中的数据的示例。因为它是一个对象和阵列的组合,人们必须使用的组合.[]其中它们都是适用的。

var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
var json = {"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"firstName":"John"},{"lastName":"Smith"}]};

localStorage.setItem('added-items', AddToLocalStorage(string));
localStorage.setItem('added-items', AddToLocalStorage(json));

// this function converts JSON into string to be entered into localStorage
function AddToLocalStorage(data) {
  if (typeof data != "string") {data = JSON.stringify(data);}
  return data;
}

// this function gets string from localStorage and converts it into JSON
function GetFromLocalStorage(key) {
  return JSON.parse(localStorage.getItem(key));
}

var myData = GetFromLocalStorage("added-items");

console.log(myData.items[2].firstName)    // "John"

myData.items[2].firstName = ["John","Elizabeth"];
myData.items[2].lastName = ["Smith","Howard"];

console.log(myData.items[2])    // {"firstName":["John","Elizabeth"],"lastName":["Smith","Howard"]}

console.log(myData.items.length)    // 4

回答by Donnie D'Amato

JSON.parseis definitely the best way to create an object but I just want to add if that doesn't work (because of lack of support), obj = eval('(' + str + ')');should work. I've had a problem with a HTML to PDF converter in the past that didn't include JSON.parseand evaldid the trick. Try JSON.parsefirst.

JSON.parse绝对是创建对象的最佳方式,但我只想添加如果这不起作用(因为缺乏支持),obj = eval('(' + str + ')');应该起作用。过去,我在使用 HTML 到 PDF 转换器时遇到了问题,该转换器不包含JSON.parse并且eval没有解决问题。JSON.parse先试试。

Access your object: obj.items[0].Desc;

访问您的对象: obj.items[0].Desc;

回答by Abdul Basit

var object = Json.parse(retrievedObject);

Now you can access it just like an array

现在您可以像访问数组一样访问它

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

If you need more help i have some previous code where i am reading Json from local storage and making a form from that json. This code will help in understanding how to traverse that array

如果您需要更多帮助,我有一些以前的代码,我正在从本地存储读取 Json 并从该 json 制作表单。此代码将有助于理解如何遍历该数组

Json stored in localstorage

json 存储在 localstorage 中

{"form":[{"element":"input", "type":"text","name":"name","value":"value","min":"2","max":"10"}]}

JavaScript to read that json

JavaScript 读取该 json

function readJson(){
    if(!form_created){
        add_form();
    }
    var fetched_json = localStorage.getItem("json");
    var obj=JSON.parse(fetched_json);
    for(var i=0; i<obj.form.length;i++){
        var input = document.createElement(obj.form[i].element);
        input.name = obj.form[i].name;
        input.value = obj.form[i].value;
        input.type = obj.form[i].type;
        input.dataset.min = obj.form[i].min;
        input.dataset.max = obj.form[i].max;
        input.dataset.optional = obj.form[i].optional;
        
        form.insertBefore (input,form.lastChild);
    }
    alert(obj.form[0].name);
}