I have a simple array that I am trying to encode JSON and set as a cookie. I am using json2.js script to encode JSON. I use the following code to set a cookie:
jQuery(document).ready(function(){ var ids = ['1', '2']; JSON.stringify(ids); setCookie(cookieName, ids, 1); }); function setCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; }
After converting the array to JSON and registering it in the console, I get:
["1", "2"]
as I expected. Then I read the cookie with the following function
function getCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; }
When I read the cookie and registered it on the console, I get:
1,2
assuming it's a string and no longer encoded JSON object. I would like to be able to set a cookie as a JSON-encoded object, read it and parse the JSON object, and finally perform data operations. My question is, how do you send a JSON encoded object to a cookie in such a way that I can parse it as JSON when I read it?
Thanks, as always!
source share