2

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?

2
  • 1
    No, you can only store string data. But plain objects can easily converted back and forth to JSON. Commented Apr 12, 2012 at 7:18
  • @Bergi: +1 for saying "plain objects". Commented Apr 12, 2012 at 7:21

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

1

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

Can't I write like this JSON.stringify(<my object>) - this won't convert as a string ?
JSON JS says this var myJSONText = JSON.stringify(myObject, replacer);
older browsers like <IE8 dont have a JSON implementations. So best to use a library ex: github.com/douglascrockford/JSON-js (use json2.js) to stringify and/or parse strings to objects. The above code tells you what exactly has to be done.
0

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

Not any - if x is circular, or has functions, then JSON.parse(JSON.stringify(x)) will not reconstruct to x.

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.