JSON 中的多行字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2392766/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multiline strings in JSON
提问by Anonnobody
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 \nas an escape.
我正在以 JSON 格式编写一些数据文件,并希望将一些非常长的字符串值拆分为多行。使用 python 的 JSON 模块,我得到了很多错误,无论是使用\还是\n作为转义。
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...
JSON 中是否可以包含多行字符串?这主要是为了视觉舒适,所以我想我可以在我的编辑器中打开自动换行,但我只是有点好奇......
回答by YOU
JSONdoes not allow real line-breaks. You need to replace all the line breaks with \n.
JSON不允许真正的换行符。您需要将所有换行符替换为\n.
eg:
例如:
"first line
second line"
"first line
second line"
can saved with:
可以保存:
"first line\nsecond line"
"first line\nsecond line"
Note:
笔记:
for Python, this should be written as:
对于Python,这应该写成:
"first line\\nsecond line"
"first line\\nsecond line"
where \\is for escaping the backslash, otherwise python will treat \nas
the control character "new line"
where\\用于转义反斜杠,否则python将\n视为控制字符“换行”
回答by errordeveloper
I have had to do this for a small Node.js project and found this work-around:
我不得不为一个小型 Node.js 项目执行此操作,并找到了以下解决方法:
{
"modify_head": [
"<script type='text/javascript'>",
"<!--",
" function drawSomeText(id) {",
" var pjs = Processing.getInstanceById(id);",
" var text = document.getElementById('inputtext').value;",
" pjs.drawText(text);}",
"-->",
"</script>"
],
"modify_body": [
"<input type='text' id='inputtext'></input>",
"<button onclick=drawSomeText('ExampleCanvas')></button>"
],
}
This looks quite neat to me, appart from that I have to use double quotes everywhere. Though otherwise, I could, perhaps, use YAML, but that has other pitfalls and is not supported natively. Once parsed, I just use myData.modify_head.join('\n')or myData.modify_head.join(), depending upon whether I want a line break after each string or not.
这对我来说看起来很整洁,除此之外我必须在任何地方使用双引号。否则,我也许可以使用 YAML,但它还有其他缺陷,并且不受本机支持。解析后,我只使用myData.modify_head.join('\n')或myData.modify_head.join(),具体取决于我是否想要在每个字符串后换行。
回答by Mark Adelsberger
Unfortunately many of the answers here address the question of how to put a newline character in the string data. The question is how to make the code look nicer by splitting the string value across multiple lines of code. (And even the answers that recognize this provide "solutions" that assume one is free to change the data representation, which in many cases one is not.)
不幸的是,这里的许多答案解决了如何在字符串数据中放置换行符的问题。问题是如何通过将字符串值拆分为多行代码来使代码看起来更好。(甚至承认这一点的答案也提供了“解决方案”,假设人们可以自由地更改数据表示,而在许多情况下却不是这样。)
And the worse news is, there is no good answer.
更糟糕的消息是,没有好的答案。
In many programming languages, even if they don't explicitly support splitting strings across lines, you can still use string concatenation to get the desired effect; and as long as the compiler isn't awful this is fine.
在许多编程语言中,即使它们不明确支持跨行拆分字符串,您仍然可以使用字符串连接来获得所需的效果;只要编译器不是很糟糕,就可以了。
But json is not a programming language; it's just a data representation. You can't tell it to concatenate strings. Nor does its (fairly small) grammar include any facility for representing a string on multiple lines.
但是 json 不是一种编程语言;它只是一个数据表示。你不能告诉它连接字符串。它的(相当小的)语法也不包括用于在多行上表示字符串的任何工具。
Short of devising a pre-processor of some kind (and I, for one, don't feel like effectively making up my own language to solve this issue), there isn't a general solution to this problem. IF you can change the data format, then you can substitute an array of strings. Otherwise, this is one of the numerous ways that json isn't designed for human-readability.
如果没有设计某种预处理器(例如,我不想有效地编写自己的语言来解决这个问题),这个问题就没有通用的解决方案。如果您可以更改数据格式,那么您可以替换一个字符串数组。否则,这是 json 不是为人类可读性而设计的众多方式之一。
回答by Lightness Races in Orbit
Check out the specification! The JSON grammar's charproduction can take the following values:
查看规格!JSON 语法的char生成可以采用以下值:
- any-Unicode-character-except-
"-or-\-or-control-character \"\\\/\b\f\n\r\t\ufour-hex-digits
- any-Unicode-character-except-
"-or-\-or-control-character \"\\\/\b\f\n\r\t\u四位十六进制数字
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 \nand \ryou require.
换行符是“控制字符”,因此,不,您的字符串中可能没有文字换行符。但是,您可以使用您需要的\n和 的任何组合对其进行编码\r。
回答by James Gentes
JSON doesn't allow breaking lines for readability.
JSON 不允许为了可读性而换行。
Your best bet is to use an IDE that will line-wrap for you.
你最好的选择是使用一个可以为你换行的 IDE。
回答by HardlyKnowEm
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 answerfrom @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.
JSON 不允许在其数据中使用“真正的”换行符;它只能转义换行符。查看答案从@YOU。根据问题,您似乎试图通过两种方式在 Python 中转义换行符:使用行继续符 ( "\") 或"\n"用作转义符。
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.)
但请记住:如果您在 python 中使用字符串,特殊的转义字符 ( "\t", "\n") 将被转换为真正的控制字符!该"\n"会代表一个换行符,而这恰恰是在JSON非法字符的ASCII控制字符替换。(至于换行符,它只是简单地取出换行符。)
So what you need to do is to prevent Python from escaping characters. You can do this by using a raw string (put rin front of the string, as in r"abc\ndef", or by including an extra slash in front of the newline ("abc\\ndef").
所以你需要做的是防止Python对字符进行转义。您可以通过使用原始字符串(放在字符串r前面,如 in r"abc\ndef",或在换行符 ( "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.
以上两个都将,而不是用"\n"真正的换行符 ASCII 控制字符替换,将保留"\n"为两个文字字符,然后 JSON 可以将其解释为换行符转义。
回答by Sandip Nirmal
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.
将属性值写为字符串数组。就像这里给出的例子https://gun.io/blog/multi-line-strings-in-json/。这会有所帮助。
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.
我们可以轻松地迭代数组以多行方式显示内容。
回答by Lacom
Use json5 (loader) see https://json5.org/- example (by json5)
使用 json5 (loader) 见https://json5.org/- 例子 (by json5)
{
lineBreaks: "Look, Mom! \
No \n's!",
}
回答by Ivan
Is it possible to have multi-line strings in JSON?
JSON 中是否可以包含多行字符串?
Yes. I just tested this now with my Firefox web browser by pressing F12, clicking console and typing at the bottom of the screen.
是的。我刚刚通过按 F12,单击控制台并在屏幕底部键入,使用我的 Firefox Web 浏览器对此进行了测试。
x={text:"hello\nworld"}
Object x has just been created from a JSON format string containing a multi-line string.
对象 x 刚刚从包含多行字符串的 JSON 格式字符串创建。
console.log(x.text)
hello
world
x.text is displayed showing that it is a multi-line string.
显示 x.text 表明它是一个多行字符串。
These two tests show that Firefox's Javascript interpreter is happy to create and use JSON with multiline strings.
这两个测试表明 Firefox 的 Javascript 解释器很乐意创建和使用带有多行字符串的 JSON。
More tests with JSON.stringifyand JSON.parseshowed the Javascript interpreter can convert an object containing multiline strings to JSON and parse it back again with no problem at all.
有更多的测试JSON.stringify,并JSON.parse显示JavaScript解释器可以转换含有多字符串JSON对象并在所有没有问题再次解析它。
I have in the past stored the complete works of Shakespeare as a property in a JSON object and then sent it over the internet, uncorrupted.
我过去曾将莎士比亚的全集作为一个属性存储在一个 JSON 对象中,然后通过互联网将其完好无损地发送出去。
Example
例子
Here is a two line string entered over three lines
这是在三行中输入的两行字符串
x={text:"expert\
s\nex\
change"}
We can display the object
我们可以显示对象
console.log(x)
giving
给予
Object { text: "experts\nexchange" }
or the string
或字符串
console.log(x.text)
giving
给予
experts
exchange
The end of lines in the string result from using \n and the multiple input lines are achieved using just \ at the end of the line.
字符串中的行尾是使用 \n 产生的,而多行输入行仅使用行尾的 \ 来实现。
In practice you might want to synchronize your line endings with the ones in the string, e.g.
在实践中,您可能希望将行尾与字符串中的行尾同步,例如
x={text:"experts\n\
exchange"}
Multi-Line String Length
多行字符串长度
console.log("Hello\nWorld".length)
11
console.log("Hello World".length)
11
Note that the string with the newline is not longer than the string with the space. Even though two characters were typed on the keyboard ('\' and 'n'), only one character is stored in the string.
请注意,带换行符的字符串不长于带空格的字符串。即使在键盘上输入了两个字符('\' 和 'n'),字符串中也只存储了一个字符。
回答by Sikander
Use regex to replace all occurrences of \r\nwith \\n.
使用正则表达式替换所有出现的\r\nwith \\n。
This worked for me in scala.
这在 Scala 中对我有用。
val newstr = str.replace("\r\n", "\n")

