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>

3 Answers 3

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"
}
Sign up to request clarification or add additional context in comments.

3 Comments

One quick question - will localstorage be ideal replacement for storing data in it instead of storing into session ?
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.
I think the OP talks about the difference between localStorage and sessionStorage. Both are on client. stackoverflow.com/a/15166867/1064270
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/

Comments

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

1 Comment

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. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.