Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails escape_javascript creates invalid JSON by escaping single quotes

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?

like image 427
Arrel Avatar asked Apr 26 '10 18:04

Arrel


3 Answers

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

"foo'bar".to_json
like image 149
Jamie Hill Avatar answered Nov 05 '22 07:11

Jamie Hill


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?

like image 20
Arrel Avatar answered Nov 05 '22 07:11

Arrel


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)}");
like image 5
Shannon E. Avatar answered Nov 05 '22 08:11

Shannon E.