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 badges1 Answer
Reset to default 7The 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
版权声明:本文标题:Parsing JSON string in Rails from Cookie generated by JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745202275a2647444.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论