Rails escape_javascript creates invalid JSON by escaping single quotes

前端 未结 5 1349
悲&欢浪女
悲&欢浪女 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条回答
  •  闹比i
    闹比i (楼主)
    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?

提交回复
热议问题