views:

465

answers:

3

The escape_javascript method in ActionView escapes the apostrophe ' as backslash apostrophe \', which gives errors when parsing as JSON.

For example, the message "I'm here" is valid JSON when printed as:

{"message": "I'm here"}

But, <%= escape_javascript("I'm here") %> outputs "I\'m here", resulting in invalid JSON:

{"message": "I\'m here"}

Is there a patch to fix this, or an alternate way to escape strings when printing to JSON?

A: 

May need more details here, but JSON strings must use double quotes. Single quotes are okay in JavaScript strings, but not in JSON.

Jakob Kruse
Thanks for the response - I added an example for clarity.
Arrel
A: 

I ended up adding a new escape_json method to my application_helper.rb, based on the escape_javascript method found in ActionView::Helpers::JavaScriptHelper:

JSON_ESCAPE_MAP = {
    '\\'    => '\\\\',
    '</'    => '<\/',
    "\r\n"  => '\n',
    "\n"    => '\n',
    "\r"    => '\n',
    '"'     => '\\"' }

def escape_json(json)
  json.gsub(/(\\|<\/|\r\n|[\n\r"])/) { JSON_ESCAPE_MAP[$1] }
end

Anyone know of a better workaround than this?

Arrel
I don't know much about Rails. But is there any way you can use `render :json` as described at http://guides.rubyonrails.org/layouts_and_rendering.html#rendering-json and http://api.rubyonrails.org/classes/ActionController/Base.html
Matthew Flaschen
That works for converting objects, but not sure about strings. I'll look into it...
Arrel
+1  A: 

Just call .to_json on a string and it will be escaped properly e.g.

"foo'bar".to_json
Jamie Hill