Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing JSON string in Rails from Cookie generated by JavaScript

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.

like image 267
Raymond Kao Avatar asked Nov 21 '11 19:11

Raymond Kao


1 Answers

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));
like image 76
Raymond Kao Avatar answered Sep 28 '22 07:09

Raymond Kao