How to store and retrieve JSON data in local storage?

I have this code:

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

This code will use localStorage.

Here is the code for retrieving the saved data:

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

My problem now is how can I get the size of the data items? the answer should be 2.

How can I get "Item1" and "Item2"?

I tried retrievedObject[0][0] but it does not work.

And how to add data to it? therefore he will

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

Can I use JSON.stringify ?

+7
json javascript local-storage
source share
5 answers
 var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}'; localStorage.setItem('added-items', JSON.stringify(string)); 

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

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

None of them have anything to do with getting the size of the array. With proper JavaScript coding, you almost never use JSON.parse or JSON.stringify . Only if serialization is clearly required.

Use length for the size of the array:

 var obj = {"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"Desc":"Item3"}]} console.debug(obj.items.length); 
+7
source share
 // 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); 
+4
source share

To give clarity to future people who may stumble upon this question and find an acceptable answer, so as not to be everything that you hoped and dreamed for:

I expanded the question so that the user can either enter string or JSON in localStorage .

Two functions are included in the package: AddToLocalStorage(data) and GetFromLocalStorage(key) .

With AddToLocalStorage(data) , if your input is not string (like JSON ), it will be converted to one.

GetFromLocalStorage(key) retrieves data from localStorage specified key

At the end of the script, an example of how to view and modify data in JSON is shown. Since this is a combination of objects and an array, you must use a combination . and [] where applicable.

 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 
+3
source share

JSON.parse is by far the best way to create an object, but I just want to add, if this does not work (due to lack of support), obj = eval('(' + str + ')'); must work. In the past, I had a problem with an HTML to PDF converter that did not include JSON.parse and eval . First try JSON.parse .

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

0
source share
 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

If you need more help, I have the previous code where I read Json from local storage and make a form from this json. This code will help you figure out how to get through this array.

Json is stored in localstorage

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

Javascript to read that 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); } 
-one
source share

All Articles