Skip to content Skip to sidebar Skip to footer

Javascript - Can We Set Javascript Objects In Cookies?

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?

Solution 1:

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.

Solution 2:

You can convert Object to JSON before save to cookies, and convert from JSON to Object after get from cookies.

Solution 3:

this function will convert the object into string use it to stringify the object and then add to cookie.

functionJSONToString(Obj){

var outStr ='';
for (var prop inObj) {
    outStr = '{';
    if (Obj.hasOwnProperty(prop)) {
        if(typeofObj[prop] == 'object'){
            outStr += JSONToString(Obj[prop]);
        } else {
            outStr += prop + ':' + Obj[prop].toString();
        }
    }  
    outStr += '}';
}
return outStr;
}

Solution 4:

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.

Post a Comment for "Javascript - Can We Set Javascript Objects In Cookies?"