Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 946
richzilla Avatar asked Mar 31 '11 15:03

richzilla


People also ask

Can you store JSON in cookie?

I think it's okay to store JSON in cookies, but as per curl.se/rfc/cookie_spec.html about the value: "This string is a sequence of characters excluding semi-colon, comma and white space". So you have to use something like encodeURIComponent(value) before storing the cookie.

Can you store object in cookie?

Store objects in the CookiesThe cookies store information in the string format only. If users want to store any other types of data in the cookies, they need to convert it to the string using the stringify() method. In this section, we will convert the object to a string and store it in cookies.

Can you store objects in JSON?

JSON is perfect for storing temporary data. For example, temporary data can be user-generated data, such as a submitted form on a website. JSON can also be used as a data format for any programming language to provide a high level of interoperability.

What is JSON how is it useful for sending and storing data?

JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa).


1 Answers

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)
like image 163
Eyal Ch Avatar answered Sep 20 '22 14:09

Eyal Ch