Multiline strings in JSON

2018-12-31 16:25发布

I'm writing some data files in JSON format and would like to have some really long string values split over multiple lines. Using python's JSON module I get a whole lot of errors, whether I use \ or \n as an escape.

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...

19条回答
梦醉为红颜
2楼-- · 2018-12-31 16:52

Check out the specification! The JSON grammar's char production can take the following values:

  • any-Unicode-character-except-"-or-\-or-control-character
  • \"
  • \\
  • \/
  • \b
  • \f
  • \n
  • \r
  • \t
  • \u four-hex-digits

Newlines are "control characters" so, no, you may not have a literal newline within your string. However you may encode it using whatever combination of \n and \r you require.

查看更多
唯独是你
3楼-- · 2018-12-31 16:53

JSON doesn't allow breaking lines for readability.

Your best bet is to use an IDE that will line-wrap for you.

查看更多
浅入江南
4楼-- · 2018-12-31 16:57

{{name}}
{{name1}}

my.opt.push({'name':'line1','name1':'line2')

查看更多
倾城一夜雪
5楼-- · 2018-12-31 16:58

Write property value as a array of strings. Like example given over here https://gun.io/blog/multi-line-strings-in-json/. This will help.

We can always use array of strings for multiline strings like following.

{
    "singleLine": "Some singleline String",
    "multiline": ["Line one", "line Two", "Line Three"]
} 

And we can easily iterate array to display content in multi line fashion.

查看更多
不流泪的眼
6楼-- · 2018-12-31 16:58

Use json5 (loader) see https://json5.org/ - example (by json5)

{ lineBreaks: "Look, Mom! \ No \n's!", }

查看更多
闭嘴吧你
7楼-- · 2018-12-31 17:01

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, above. 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.

查看更多
登录 后发表回答