Hadi Ranjbar
Hadi Ranjbar

Reputation: 1802

Saving an array to cookies in javascript

I am trying to save an array in cookies:

setCookie("a", JSON.stringify([{a:1},{a:2}]))

But seems that browser stores a decoded version of my string and when I try to retrieve it:

JSON.parse(getCookie("a"))

I get parsing error. What is the solution to solve this problem?

Upvotes: 1

Views: 3620

Answers (3)

Karthick
Karthick

Reputation: 381

try to serialize the JSON data into single String and saving it in the cookie while read it back unserialize the String and convert it back to JSON string or JSON object

Upvotes: 0

Arun Saini
Arun Saini

Reputation: 7814

Here is how to create/get a cookie with array value in javascript

JSON encode it, effectively producing a string like "{name:'myname',age:'myage'}" which you put in a cookie, retrieve when needed and decode back into a JavaScript array/object.

Example - store array in a cookie:

var arr = ['foo', 'bar', 'baz'];
var json_str = JSON.stringify(arr);
createCookie('mycookie', json_str);

Later on, to retrieve the cookie's contents as an array:

var json_str = getCookie('mycookie');
var arr = JSON.parse(json_str);

Note: cookie functions are not native, taken from How do I create and read a value from cookie? , see below:

    var createCookie = function(name, value, days) {
    var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else {
        expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) {
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

Upvotes: 3

Patrick
Patrick

Reputation: 457

Try to use createCookie and getCookie. It gives you a parser error because getCookie("a") returns undefined.

Upvotes: 0

Related Questions