Search code examples
javascriptjqueryjsonstringify

jQuery: JSON.stringify changes my object value after saving in cookie


Possible Duplicate:
Allowed characters in cookies

I'm using JSON.stringify to convert an object to save it in a cookie. But after saving Arabic Windows-1256 encoding in a cookie, I wasn't able to restore it. Here's what I did:

For example:

Convert and save in a cookie.

conv[user]   = {"user":1,"u":1,"m":3,"c":255,"comment":'السلام عليكم ورحمه الله'};
addCookie('chat_conversations', JSON.stringify(conv) , 7);

Restore value from cookie:

var con  = is_cookie('chat_conversations');
conv = jQuery.parseJSON(con);

Getting my JSON result:

alert(conv[1].comment);

Result

"'D3D'E 9DJCE H1-EG 'DDG H(1C'*G\n"

Here's the result of my cookie

chat_conversations={"1":{"user":"1","u":"1","m":3,"c":255,"comment":"'D3D'E 9DJCE H1-EG 'DDG H(1C'*G\n"}}; expires=Sat, 08 Dec 2012 15:00:42 GMT; path=/; domain=127.0.0.1

How can I save an object containing Arabic in a cookie and restore it?


Solution

  • You should sanatise strings going into a cookie using escape or encodeURIComponent (minor differences between the two, see below) and then reverse this via unescape or decodeURICompontent when retrieving the data.

    // Create obj using safe chars only
    conv[user] = {
        "user" : 1, // (numbers are fine as they are)
        "u" : 1,
        "m" : 3,
        "c" : 255,
        "comment" : escape('السلام عليكم ورحمه الله') // by escaping potentially unsafe chars
    };
    // save
    addCookie('chat_conversations', JSON.stringify(conv) , 7);
    // retrieve
    var con  = is_cookie('chat_conversations');
    conv = jQuery.parseJSON(con);
    
    var comment = unescape(conv[1].comment); // unescape what was escaped earlier
    alert(comment);
    // "السلام عليكم ورحمه الله"
    

    escape is fine because you just want to use this data in JavaScript. If you want to access the cookie server-side then I'd strongly recommend using encodeURIComponent.

    If you are just using it for JavaScript, consider window.localStorage because it will cause less internet usage.