JMA
JMA

Reputation: 994

How to store and retrieve JSON data into 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 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.

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

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

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

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

Can I use JSON.stringify?

Upvotes: 16

Views: 83223

Answers (5)

user663031
user663031

Reputation:

// 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);

Upvotes: 8

zack
zack

Reputation: 95

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 string or JSON into localStorage.

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

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

GetFromLocalStorage(key) retrieves the data from localStorage of said 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.

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

Upvotes: 6

Daniel W.
Daniel W.

Reputation: 32260

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

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

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

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.

Use length for the size of the array:

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

Upvotes: 17

Donnie D'Amato
Donnie D'Amato

Reputation: 3940

JSON.parse is 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.parse and eval did the trick. Try JSON.parse first.

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

Upvotes: 0

Abdul Basit
Abdul Basit

Reputation: 374

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 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 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);
}

Upvotes: -1

Related Questions