How do I handle newlines in JSON?

后端 未结 10 1631
后悔当初
后悔当初 2020-11-22 05:28

I\'ve generated some JSON and I\'m trying to pull it into an object in JavaScript. I keep getting errors. Here\'s what I have:

var data = \'{\"count\" : 1, \         


        
10条回答
  •  感动是毒
    2020-11-22 06:10

    According to the specification, http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf:

    A string is a sequence of Unicode code points wrapped with quotation marks (U+0022). All characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark (U+0022), reverse solidus (U+005C), and the control characters U+0000 to U+001F. There are two-character escape sequence representations of some characters.

    So you can't pass 0x0A or 0x0C codes directly. It is forbidden! The specification suggests to use escape sequences for some well-defined codes from U+0000 to U+001F:

    • \f represents the form feed character (U+000C).
    • \n represents the line feed character (U+000A).

    As most of programming languages uses \ for quoting, you should escape the escape syntax (double-escape - once for language/platform, once for JSON itself):

    jsonStr = "{ \"name\": \"Multi\\nline.\" }";
    

提交回复
热议问题