JSON encoded array converted to string when saved as a cookie

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!

+4
source share
3 answers

Change this:

 JSON.stringify(ids); setCookie(cookieName, ids, 1); 

For this:

 var str = JSON.stringify(ids); setCookie(cookieName, str, 1); 
+6
source

I do not see that you are really using the result with a JSON string:

 jQuery(document).ready(function(){ var ids = ['1', '2']; setCookie(cookieName, JSON.stringify(ids), 1); }); 

Try this instead

+2
source

Do not use these cookie functions, they are erroneous. setCookie fails to correctly encode the name and value, and getCookie for cookies with a common suffix (see my answer on javascript getCookie functions ).

For setCookie I would use this:

 function setCookie(name, value, days) { var expires = ""; if (days > 0) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); expires = "; expires="+date.toGMTString(); } document.cookie = encodeURIComponent(name)+"="+encodeURIComponent(value)+expires+"; path=/"; } 
+2
source

All Articles