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

后端 未结 4 1961
陌清茗
陌清茗 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: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: ""})
    # => "{\"name\":\"\"}"
    
    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 :)

提交回复
热议问题