admin管理员组

文章数量:1415119

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 ma (',') 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 ma (',') 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 ma it encounters.

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

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 ma (',') 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 ma (',') 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 ma it encounters.

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

Share Improve this question edited Nov 22, 2011 at 4:38 Raymond Kao asked Nov 21, 2011 at 19:32 Raymond KaoRaymond Kao 1572 silver badges8 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

The ma 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));

本文标签: Parsing JSON string in Rails from Cookie generated by JavaScriptStack Overflow