Sriram
Sriram

Reputation: 2999

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?

Upvotes: 2

Views: 3061

Answers (4)

Satish N Ramteare
Satish N Ramteare

Reputation: 197

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;
}

Upvotes: 1

Joseph
Joseph

Reputation: 119847

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.

Upvotes: 5

Boyo
Boyo

Reputation: 1381

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

Upvotes: 4

Serge
Serge

Reputation: 1601

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.

Upvotes: 0

Related Questions