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

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

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


当前回答

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

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

其他回答

这是一个非常老的问题,但当我想提高使用复杂条件表达式的Vega JSON规范代码的可读性时,我也有同样的问题。代码是这样的。

正如这个答案所说,JSON不是为人类设计的。我知道这是一个历史性的决定,它对数据交换的目的是有意义的。然而,JSON仍然被用作这种情况下的源代码。所以我要求我们的工程师使用Hjson作为源代码,并将其处理成JSON。

例如,在Git For Windows环境中, 你可以下载Hjson命令行的二进制文件,放在git/bin目录下使用。 然后,转换(转译)Hjson源为JSON。使用自动化工具(如Make)将有助于生成JSON。

$ which hjson
/c/Program Files/git/bin/hjson

$ cat example.hjson
{
  md:
    '''
    First line.
    Second line.
      This line is indented by two spaces.
    '''
}

$ hjson -j example.hjson > example.json

$ cat example.json
{
  "md": "First line.\nSecond line.\n  This line is indented by two spaces."
}

如果要在编程语言中使用转换后的JSON,特定于语言的库(如hjson-js)将非常有用。

我注意到在一个重复的问题中张贴了同样的想法,但我想分享更多的信息。

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

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

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

eg:

"first line
second line"

可以通过以下方式保存:

“一线/二线”

注意:

对于Python,这应该写成:

“一线、二线”

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

假设这个问题与轻松编辑文本文件,然后手动将它们转换为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.

我曾经在一个小型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>"
 
 ],
}

一旦解析,我只使用myData.modify_head.join('\n')或myData.modify_head.join(),这取决于我是否想在每个字符串后换行。

这看起来很整洁,除了我必须在所有地方使用双引号。尽管在其他情况下,我也许可以使用YAML,但它有其他缺陷,并且本机不支持。