简体   繁体   中英

Why aren't double quotes and backslashes allowed in strings in the JSON standard?

If I run this in a JavaScript console in Chrome or Firebug, it works fine.

JSON.parse('"\u0027"') // Escaped single-quote

But if I run either of these 2 lines in a Javascript console, it throws an error.

JSON.parse('"\u0022"') // Escaped double-quote
JSON.parse('"\u005C"') // Escaped backslash

RFC 4627 section 2.5 seems to imply that \\ and " are allowed characters as long as they're properly escaped. The 2 browsers I've tried this in don't seem to allow it, however. Is there something I'm doing wrong here or are they really not allowed in strings? I've also tried using \\" and \\\\ in place of " and \\ respectively.

I feel like I'm just doing something very wrong, because I find it hard to believe that JSON would not allow these characters in strings, especially since the specification doesn't seem to mention anything that I could find saying they're not allowed.

You need to quote the backslash!

that which we call a rose

By any other name would smell as sweet

A double quote is a double quote, no matter how you express it in the string constant. If you put a backslash before your \\u\u003c/code> expression within the constant, then the effect is that of a backslash-quoted double-quote, which is in fact what you've got.

The most interesting thing about your question is that it helps me realize that every JavaScript string parser I've ever written is wrong.

JavaScript is interpreting the Unicode escape sequences before they get to the JSON parser. This poses a problem:

  • '"\'"' unquoted the first time (by JavaScript): "'"
    The second time (by the JSON parser) as valid JSON representing the string: '

  • '"""' unquoted the first time (by JavaScript): """
    The JSON parser sees this unquoted version """ as invalid JSON (does not expect the last quotation mark).

  • '"\\"' unquoted the first time (by JavaScript): "\\"
    The JSON parser also sees this unquoted version "\\" as invalid JSON (second quotation mark is backslash-escaped and so does not terminate the string).

The fix for this is to escape the escape sequence, as \\\\u.... In reality, however, you would probably just not use the JSON parser. Used in the correct context (ensured by wrapping it within parentheses, all JSON is valid JavaScript.

You are not escaping the backslash and the double-quote, as \\u00xx is being interpreted by the javascript parser.

JSON.parse('"\\\u0022"')
JSON.parse('"\\\""')

and

JSON.parse('"\\\u005C"')
JSON.parse('"\\\\"')

work as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM