Setting an array of objects to sessionStorage
Asked Answered
U

1

15

Ok, so I have this JSON:

{"Status":"OK!","ListaPermessi":
[{"IdPermesso":10,"Nome":"WIND_PARAMS"},
 {"IdPermesso":11,"Nome":"ADMIN_SERVER"},
 {"IdPermesso":21,"Nome":"REC"},
 {"IdPermesso":22,"Nome":"REC_DIST"},
 {"IdPermesso":23,"Nome":"REC_DIST_CR"}
]}

My code is:

var parsedResult = JSON.parse(result); // where result is the above JSON
if (parsedResult.Status === "OK!") {
    // Set sessionStorage vars
    if (typeof(Storage) !== "undefined") {
        // localStorage & sessionStorage support!

        sessionStorage.setItem("ListaPermessi", parsedResult.ListaPermessi);
    }
    else {
        // Sorry! No web storage support :(
    }
}

But... this is not working properly! After the assignment, the sessionStorage seen from Firebug looks like this:

sessionStorage:

  • ListaPermessi = "[object Object],[object Object],[object Object],[object Object],[object Object]"

What is the proper way to assign an array of objects to a sessionStorage variable from javascript?

Unlace answered 24/9, 2012 at 10:4 Comment(0)
Q
32

You need to turn it back into a JSON string. You can do that with the JSON.stringify method:

sessionStorage.setItem("ListaPermessi", JSON.stringify(parsedResult.ListaPermessi));

The reason for this is that web storage can only store strings, and the default toString method of Object returns, as you've now seen, "[object Object]".


Side note: typeof is an operator, not a function, so there's no need for the parentheses:

if (typeof Storage !== "undefined") { //...
Quindecennial answered 24/9, 2012 at 10:6 Comment(6)
Thanks for the quick answer! But, still not working! I've tried it and it parses the list as a string, not as an array of objects.Unlace
@CosminT. - What do you mean? What is the result of JSON.stringify(parsedResult.ListaPermessi)?Quindecennial
"[{"IdPermesso":10,"Nome":"WIND_PARAMS"}, {"IdPermesso":11,"Nome":"ADMIN_SERVER"}, {"IdPermesso":21,"Nome":"REC"}, {"IdPermesso":22,"Nome":"REC_DIST"}, {"IdPermesso":23,"Nome":"REC_DIST_CR"} ]". as a string, between ""Unlace
@CosminT. - That's what you should get. You can only store strings in web storage. You can call JSON.parse on that value to convert it back into an actual JS data structure.Quindecennial
That's the answer I was looking for! So it cannot have "an array structure". Thanks a lot!Unlace
@CosminT. - You're welcome, glad I could help :) Just remember to always call JSON.stringify when storing, and JSON.parse when retrieving data to/from web storage.Quindecennial

© 2022 - 2024 — McMap. All rights reserved.