I'm trying to put one javascript object in Cookies but somehow it is getting converted as String object. Is there any way we can set Objects in JavaScript cookies?
-
1No, you can only store string data. But plain objects can easily converted back and forth to JSON.Bergi– Bergi2012-04-12 07:18:49 +00:00Commented Apr 12, 2012 at 7:18
-
@Bergi: +1 for saying "plain objects".Amadan– Amadan2012-04-12 07:21:44 +00:00Commented Apr 12, 2012 at 7:21
4 Answers
You can use JSON.stringify() to turn the object into a JSON string and store it. Then when you read them, turn the string to an Object using JSON.parse()
also, it's better to use LocalStorage instead of cookies to store larger data. Both store strings, but cookies are only 4kb while LocalStorage are around 5-10MB.
Comments
this function will convert the object into string use it to stringify the object and then add to cookie.
function JSONToString(Obj){
var outStr ='';
for (var prop in Obj) {
outStr = '{';
if (Obj.hasOwnProperty(prop)) {
if(typeof Obj[prop] == 'object'){
outStr += JSONToString(Obj[prop]);
} else {
outStr += prop + ':' + Obj[prop].toString();
}
}
outStr += '}';
}
return outStr;
}
3 Comments
Use JSON - JavaScript Object Notation. Here's a nice tutorial on using JSON.
Long things short: it's a standard of converting any object to a specially formatted text string, and back. So you would store a JSON string in the cookie.
1 Comment
x is circular, or has functions, then JSON.parse(JSON.stringify(x)) will not reconstruct to x.