Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am trying to parse a JSON string that is stored inside a cookie value that my Rails code is calling.

Rails is able to read the string up until the comma (',') that separates the two different key:value pairs in the string.

JavaScript:

var value1 = "v1";
var value2 = "v2";
var obj = { key1: value1, key2: value2 };
document.cookie = "cookiename="+JSON.stringify(obj);

Cookie:

Name: cookiename
Content: {"key1":v1,"key2":v2}

Rails:

@cookievalue = cookies[:cookiename]

Rails when calling @cookievalue in an erb <%= @cookievalue %> evaluates it as:

{"key1":v1

anything past the comma (',') that separates key1:v1,key2:v2 is missing.

Any ideas?

I tried this as straight text and it does the same thing with the first comma it encounters.

UPDATED Answered my own question below - needed to escape the comma separating the values using an encode() in JS.

share|improve this question
add comment

1 Answer

up vote 3 down vote accepted

The comma is not a valid character (I obviously over looked this) and as such it dropped everything after it.

UPDATED FIX:

added an encodeURIComponent() to the JavaScript:

document.cookie = "cookiename="+encodeURIComponent(JSON.stringify(obj));

This escapes the characters properly and passes the JSON formatted string to my server properly. Also used encodeURIComponent() instead of encode() because of Asian or Asiatic characters not encoding properly with encode().

Server side change (Optional):

@cookievalue = JSON.parse(cookies[:cookiename])

This allows me to parse the JSON string a bit easier once retrieved from cookie[:cookiename]

Previous Fix:

added an encode() to the JavaScript:

document.cookie = "cookiename="+encode(JSON.stringify(obj));
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.