Rails escape_javascript creates invalid JSON by escaping single quotes

前端 未结 5 1360
悲&欢浪女
悲&欢浪女 2021-02-07 05:54

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

For

相关标签:
5条回答
  • 2021-02-07 06:27

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

    "foo'bar".to_json
    
    0 讨论(0)
  • 2021-02-07 06:33

    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)}");
    
    0 讨论(0)
  • 2021-02-07 06:34

    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")) %>
    
    0 讨论(0)
  • 2021-02-07 06:36

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

    0 讨论(0)
  • 2021-02-07 06:47

    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?

    0 讨论(0)
提交回复
热议问题