How to safely embed JSON with [removed] in HTML document?

后端 未结 4 1931
陌清茗
陌清茗 2020-12-30 01:16

In a Rails 3.1 app, how can I safely embed some JSON data into an HTML document?

Suppose I have this in a controller action:

@tags = [
    {name:\"ta         


        
相关标签:
4条回答
  • 2020-12-30 01:23

    Your code using just @tags.to_json works in rails3, if you enable it with:

       ActiveSupport.escape_html_entities_in_json = true
    

    Otherwise, your other option is this:

       var tags_list = <%= raw @tags.to_json.gsub("</", "<\\/") %>;
    

    This saves the client having to parse the whole thing through $

    0 讨论(0)
  • 2020-12-30 01:23

    I think that if you try this it will work:

    var tags_list = "<%== @tags.to_json.gsub('/', '\/') %>";
    

    (Notice the double == and the " ")

    0 讨论(0)
  • 2020-12-30 01:24

    btw, this works but is not a good solution in my opinion:

    <script type="text/javascript" charset="utf-8">
      //<![CDATA[
      var tags_list = <%=raw @tags.to_json.gsub('/', '\/') %>;
      // ]]>
    </script>
    
    0 讨论(0)
  • 2020-12-30 01:39

    The proper way in 2019 is to wrap obj.to_json with json_escape function. json_escape is directly intended for escaping specific HTML symbols inside JSON strings. Example below from the documentation:

    json = JSON.generate({ name: "</script><script>alert('PWNED!!!')</script>"})
    # => "{\"name\":\"</script><script>alert('PWNED!!!')</script>\"}"
    
    json_escape(json)
    # => "{\"name\":\"\\u003C/script\\u003E\\u003Cscript\\u003Ealert('PWNED!!!')\\u003C/script\\u003E\"}"
    
    JSON.parse(json) == JSON.parse(json_escape(json))
    # => true
    

    It seems this page appears on top of Google Search results, that's why I decided to provide a comment with an update :)

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