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.
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.
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.
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.
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).
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With