Rails:
object = Object.find_by(params[:id])
object_items = { "1" => { :id => "123456", :name => "Pancakes Yum!" }, "2" => { :id => "789010", :name => "hello 123" }}
cookies[:something] = { "id" => object.id, "title" => object.title, "object_items" => object_items }.to_json
Let’s say that object.title produces a string “Hello World”
Cookie Content:
%7B%22id%22%3A2%2C%22title%22%3A%22Hello+World%22%2C%22object_items%22%3A%7B%221%22%3A%7B%22id%22%3A%22123456%22%2C%22name%22%3A%22Pancakes+Yum!%22%7D%2C%222%22%3A%7B%22id%22%3A%22789010%22%2C%22name%22%3A%22hello+123%22%7D%7D%7D
Problem:
The JSON string being created replaces/escapes whitespace with a plus sign (+) instead of %20 which means that if I were to read the string and grab the value for object.title in HTML/JavaScript it will read it as “Hello+World” and not “Hello World” as expected.
All other characters seem to be replaced/escaped properly – is it because the space exists inside a double quote? I can’t figure out why it’s producing this string as it is.
I don’t understand why you are communicating with the client via cookies. Why not use a controller action and ajax request?
Then request it using jQuery or something like this:
What’s the point in using Rails if you’re not going to use Rails?
Cookies are CGI escaped before being sent to the client. When the client retransmits them Rails unescapes them.
You can test the behaviour like this: