是否有可能在JSON中有多行字符串?

这主要是为了视觉上的舒适,所以我想我可以在编辑器中打开自动换行,但我只是有点好奇。

我正在编写JSON格式的一些数据文件,并希望有一些非常长的字符串值分割在多行。使用python的JSON模块,无论我使用\或\n作为转义,我都会得到很多错误。


当前回答

\n\r\n为我工作!!

\n表示单行换行,\n\r\n表示双行换行

其他回答

将属性值写入字符串数组。比如这里给出的例子https://gun.io/blog/multi-line-strings-in-json/。这将有所帮助。

我们总是可以使用数组的字符串多行字符串,如下所示。

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

我们可以很容易地迭代数组以多行方式显示内容。

假设这个问题与轻松编辑文本文件,然后手动将它们转换为json有关,我发现了两个解决方案:

hjson (that was mentioned in this previous answer), in which case you can convert your existing json file to hjson format by executing hjson source.json > target.hjson, edit in your favorite editor, and convert back to json hjson -j target.hjson > source.json. You can download the binary here or use the online conversion here. jsonnet, which does the same, but with a slightly different format (single and double quoted strings are simply allowed to span multiple lines). Conveniently, the homepage has editable input fields so you can simply insert your multiple line json/jsonnet files there and they will be converted online to standard json immediately. Note that jsonnet supports much more goodies for templating json files, so it may be useful to look into, depending on your needs.

\n\r\n为我工作!!

\n表示单行换行,\n\r\n表示双行换行

JSON不允许真正的换行。您需要将所有换行符替换为\n。

eg:

"first line
second line"

可以通过以下方式保存:

“一线/二线”

注意:

对于Python,这应该写成:

“一线、二线”

\\是用来转义反斜杠的,否则python会把\n当作 控制字符“new line”

如果只是为了在编辑器中显示,你可以使用'代替'或'

const obj = {
myMultiLineString: `This is written in a \
multiline way. \
The backside of it is that you \
can't use indentation on every new \
line because is would be included in \
your string. \
The backslash after each line escapes the carriage return. 
`
}

例子:

console.log(`First line \
Second line`);

将放在控制台: 一线二线

console.log(`First line 
second line`);

将放在控制台: 第一行 第二行

希望这回答了你的问题。