richzilla
richzilla

Reputation: 41992

storing and retrieving json objects to / from a cookie

Im attempting to store json objects in a cookie, but im running into a few problems. I can create my object like this:

product = {
   "name" : "prodname",
   "quantity" : 4
}

i then save this object in my cookie. As more products are added (its a shopping basket) i add further strings by appending new objects onto the end of the cookie string (so i essentially have lots of small seperate objects) . Im having trouble getting the objects back out of the cookie string though. Both $.parseJSON and eval fail when i attempt to read the objects back from the cookie. Any help would be appreciated.

Upvotes: 8

Views: 23907

Answers (2)

Eyal Ch
Eyal Ch

Reputation: 10056

its not a good practice to save the value that returned from JSON.stringify(cookieStr) to the cookie. it can lead to a bug in some browsers.

before using it you should convert it to base64 (using btoa), and when reading it, converting from base64 (using atob)

val = JSON.stringify(cookieStr)
val = btoa(val)

write_cookie(val)

Upvotes: 10

Matthew Flaschen
Matthew Flaschen

Reputation: 284796

It should probably be like:

{"products": [
    {
       "name" : "prodname",
       "quantity" : 4
    },
    {
       "name" : "prodname2",
       "quantity" : 3
    }
]}

The [] signifies an array. When you want add another product, you load it from the cookie, update the array, then save it again. If you wanted, you could skip the outer object and have the cookie just be the array.

EDIT: Say cookieStr is your cookie.

var root = $.parseJSON(cookieStr);
root.products.push(newProduct);
cookieStr = JSON.stringify(root);

Upvotes: 8

Related Questions