Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
5
rated 0 times [  9] [ 4]  / answers: 1 / hits: 22239  / 13 Years ago, thu, march 31, 2011, 12:00:00

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.


More From » json

 Answers
13

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

[#92985] Wednesday, March 30, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shaynelandenb

Total Points: 293
Total Questions: 97
Total Answers: 94

Location: Monaco
Member since Fri, Sep 24, 2021
3 Years ago
shaynelandenb questions
Tue, Jan 25, 22, 00:00, 2 Years ago
Wed, Nov 10, 21, 00:00, 3 Years ago
Wed, Apr 21, 21, 00:00, 3 Years ago
;