Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing JSON array in HTML5 storage not working

Here is my HTML code, Here i am storing json Array in localstorage. I want to iterate json later anytime but its showing it undefined. How can i iterate over stored json Array using js ?

<!DOCTYPE html>
<html>
<head>
<script>
var ob=[
   {
     "id":1,
     "name":"one"
   },
   {
     "id":2,
     "name":"two"
   }
];
function clickCounter() {alert("dsdsd");
    if(typeof(Storage) !== "undefined") {
        if (sessionStorage.ob) {
            sessionStorage.ob = ob;
        } else {
            sessionStorage.ob = undefined;
        }

        alert(sessionStorage.ob[0].id);
        for (var i in sessionStorage.ob)
        {
           alert(sessionStorage.ob[i].id);
        }    

    } else {

    }
}
</script>
</head>
<body>
<button onclick="clickCounter()" type="button">Click me!</button>
</body>
</html>
like image 818
Manish Kumar Avatar asked Dec 25 '22 20:12

Manish Kumar


1 Answers

localStorage, like cookies, is for storing strings. If you attempt to store a complex object in storage it will first be cast to its string representation.

Therefore, you need to stringify when saving it and parse it back into a complex object when attempting to iterate over it later.

Save:

var obj = {foo: 'bar'};
localStorage.setItem('obj', JSON.stringify(obj)); //<-- saved as JSON string

Read later:

var obj = JSON.parse(localStorage.getItem('obj'));
for (var i in obj) {
    alert(i+' = '+obj[i]); //<-- "foo = bar"
}
like image 56
Mitya Avatar answered Dec 27 '22 11:12

Mitya