Are multi-line strings allowed in JSON?

前端 未结 9 1316
醉酒成梦
醉酒成梦 2020-11-22 04:21

Is it possible to have multi-line strings in JSON?

It\'s mostly for visual comfort so I suppose I can just turn word wrap on in my editor, but I\'m just kinda curious

9条回答
  •  感情败类
    2020-11-22 04:34

    This is a really old question, but I came across this on a search and I think I know the source of your problem.

    JSON does not allow "real" newlines in its data; it can only have escaped newlines. See the answer from @YOU. According to the question, it looks like you attempted to escape line breaks in Python two ways: by using the line continuation character ("\") or by using "\n" as an escape.

    But keep in mind: if you are using a string in python, special escaped characters ("\t", "\n") are translated into REAL control characters! The "\n" will be replaced with the ASCII control character representing a newline character, which is precisely the character that is illegal in JSON. (As for the line continuation character, it simply takes the newline out.)

    So what you need to do is to prevent Python from escaping characters. You can do this by using a raw string (put r in front of the string, as in r"abc\ndef", or by including an extra slash in front of the newline ("abc\\ndef").

    Both of the above will, instead of replacing "\n" with the real newline ASCII control character, will leave "\n" as two literal characters, which then JSON can interpret as a newline escape.

提交回复
热议问题