18

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?

Arrel
  • 13,558
  • 7
  • 26
  • 24

5 Answers5

11

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

"foo'bar".to_json
Jamie Hill
  • 134
  • 1
  • 3
7

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
  • 13,558
  • 7
  • 26
  • 24
  • 1
    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 Apr 26 '10 at 23:37
  • That works for converting objects, but not sure about strings. I'll look into it... – Arrel Apr 27 '10 at 22:08
  • Only thing I've found so far that's worked. Not sure why to_json decides to escape quotes with a single backslash instead of double but that had me for a while. Thanks. – dChimento Nov 10 '14 at 21:24
4

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
  • 2,458
  • 18
  • 17
4

I had some issues similar to this, where I needed to put Javascript commands at the bottom of a Rails template, which put strings into jQuery.data for later retrieval and use.

Whenever I had a single-quote in the string I'd get a JavaScript error on loading the page.

Here is what I did:

-content_for :extra_javascript do
  :javascript
    $('#parent_#{parent.id}').data("jsonized_children", "#{escape_javascript(parent.jsonized_children)}");
Ben
  • 51,770
  • 36
  • 127
  • 149
Shannon E.
  • 49
  • 1
  • 1
0

Already there is an issue in github/rails https://github.com/rails/rails/issues/8844

Fix to mark the string as html_safe

<%= escape_javascript("I'm here".html_safe) %>

or even better you can sanitize the string

<%= sanitize(escape_javascript("I'm here")) %>
<%= escape_javascript(sanitize("I'm here")) %>
YasirAzgar
  • 1,385
  • 16
  • 15