4

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>
Nipuna
  • 6,846
  • 9
  • 64
  • 87
Manish Kumar
  • 10,214
  • 25
  • 77
  • 147

3 Answers3

9

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"
}
Mitya
  • 33,629
  • 9
  • 60
  • 107
  • One quick question - will `localstorage` be ideal replacement for storing data in it instead of storing into session ? – Manish Kumar Apr 11 '15 at 11:41
  • 1
    Well localStorage IS sort of session data - it's just it's stored client side rather than server. Your choice should be based on the sensitivity of the data, and what environment needs to access it. JS can access data saved over localStorage, but server side languages can't, but can instead access session data. – Mitya Apr 11 '15 at 11:51
  • I think the OP talks about the difference between localStorage and sessionStorage. Both are on client. http://stackoverflow.com/a/15166867/1064270 – Gaël Barbin Apr 11 '15 at 12:23
2

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/

Gaël Barbin
  • 3,769
  • 3
  • 25
  • 52
0

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
Joshua Arvin Lat
  • 1,029
  • 9
  • 8
  • It depends if you're already using a jQuery in your project. If you're planning to do everything in pure JavaScript, then the JavaScript approach should be okay. :) – Joshua Arvin Lat Apr 11 '15 at 11:41