What do I need to escape in my HTML (JSON response)

后端 未结 4 617
野趣味
野趣味 2021-01-21 01:24

My JSON response looks like:

{rc: \"200\", test: \"\", user: \"
相关标签:
4条回答
  • 2021-01-21 01:53

    You don't need to escape HTML in a javascript string. What exactly are you trying to do/what is the problem? Take a look at the escape() function - it might help.

    0 讨论(0)
  • 2021-01-21 01:57

    You're HTML values are OK, but the keys of the JSON object must be enclosed in quotes.

    From the JSON RFC:

    2.2. Objects

    An object structure is represented as a pair of curly brackets
    surrounding zero or more name/value pairs (or members). A name is a
    string.

    and

    2.5. Strings

    The representation of strings is similar to conventions used in the C
    family of programming languages. A string begins and ends with
    quotation marks.

    Also, if you output this JSON object inside the script tags of an HTML page, you must escape the "</" sequence of HTML closing tags, as per this appendix in the HTML 4 specification.

    0 讨论(0)
  • 2021-01-21 02:03

    In your example, you won't have to escape anything. But, if the HTML comes with double quotes, you'll have to escape them, obviously.

    0 讨论(0)
  • 2021-01-21 02:18

    I used jsonlint to validate your latest example, and the line breaks are what it flagged. When they were removed, it validated.

    {
        "rc": "200",
        "m" : "",
        "o": "<div class='s1'><div class='avatar'><a href='\/asdf'>asdf<\/a><br \/><strong>0<\/strong>      <\/div>    <div class='sl'><p>444444444<\/p><\/div><div class='clear'><\/div><\/div>"
    }
    
    0 讨论(0)
提交回复
热议问题