Manish Kumar
Manish Kumar

Reputation: 10502

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>

Upvotes: 4

Views: 1409

Answers (3)

Ga&#235;l Barbin
Ga&#235;l Barbin

Reputation: 3919

You can not store object, you have to stringify then parse them.

var ob=[
   {
     "id":1,
     "name":"one"
   },
   {
     "id":2,
     "name":"two"
   }
];

sessionStorage.ob= ob;
console.log(sessionStorage.ob);

sessionStorage.ob= JSON.stringify(ob);
console.log(JSON.parse(sessionStorage.ob));

http://jsfiddle.net/ofLozkhc/

Upvotes: 2

Joshua Arvin Lat
Joshua Arvin Lat

Reputation: 1039

You might want to try using a plugin instead such as this one: https://github.com/joshualat/jquery-local-storage

$.localStorage('key', 'string value')
> true

$.localStorage('key')
> "string value"

$.localStorage('json', {'a': 'b', 'c': 'd'})
> true

$.localStorage('json')['a']
> "b"

$.localStorage('json', {'a': 'b', 'c': 'd', 'e': {'f': 'g'}})
> true

$.localStorage('json')['e']['f']
> "g"

It already includes a JSON reader and stringifier:

JSON.stringify = JSON.stringify || function (obj) {
  var t = typeof (obj);
  if (t != "object" || obj === null) {
    if (t == "string") obj = '"' + obj + '"';
    return String(obj);
  } else {
    var n, v, json = [], arr = (obj && obj.constructor == Array);

    for (n in obj) {
      v = obj[n]; t = typeof(v);

      if (t == "string") v = '"'+v+'"';
      else if (t == "object" && v !== null) v = JSON.stringify(v);

      json.push((arr ? "" : '"' + n + '":') + String(v));
    }

    return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
  }
};

JSON.parse = JSON.parse || function (str) {
  if (str === "") str = '""';
  eval("var p=" + str + ";");
  return p;
};

If you want, you can just grab whatever you need here: https://github.com/joshualat/jquery-local-storage/blob/master/jquery.local-storage.js

  1. Stringify
  2. Check browser
  3. Set Local Storage Item with String

Upvotes: 0

Mitya
Mitya

Reputation: 34576

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"
}

Upvotes: 9

Related Questions