JSON 值可以包含多行字符串吗

我正在编写一个 JSON 文件,它将被 Java 程序读取。

{
"testCases" :
{
"case.1" :
{
"scenario" : "this the case 1.",
"result" : "this is a very long line which is not easily readble.
so i would like to write it in multiple lines.
but, i do NOT require any new lines in the output.
I need to split the string value in this input file only.
such that I don't require to slide the horizontal scroll again and again while verifying the correctness of the statements.
the prev line, I have shown, without splitting just to give a feel of my problem"
}
}
}
172765 次浏览

对于 说明书,JSON 语法的 Char产品可以采用以下值:

  • "\或控制字符外的任何 Unicode 字符
  • \"
  • \\
  • \/
  • \b
  • \f
  • \n
  • \r
  • \t
  • \u 四位十六进制数字

换行是“控制字符”,所以不行,您可以在字符串中使用字面换行。但是,您可以使用您需要的 \n\r的任何组合对其进行编码。

JSONLint工具确认您的 JSON 无效。


而且,如果您希望在 JSON 语法中编写换行,而不在数据中实际包含换行,那么您就更加不走运了。虽然 JSON 在一定程度上是人类友好的,但它仍然是 资料,并且您试图对该数据应用任意格式。这绝对不是 JSON 的目的。

据我所知,这个问题不是关于如何使用 json传递带有控制符号的字符串,而是关于如何在文件中存储和恢复 json,您可以在其中使用编辑器控制符号分割字符串。

如果要在文件中存储多行字符串,则文件将不存储有效的 json对象。但是如果只在程序中使用 json文件,那么可以根据需要存储数据,并在每次将数据加载到程序并传递给 json 解析器时手动删除文件中的所有换行。

或者,或者,更好的选择是,你可以有你的 json数据源文件,在那里你可以编辑一个你想要的骗局,然后删除所有新的行与一些实用工具到有效的 json文件,你的程序将使用。

我不确定你的确切要求,但一个可能的解决方案,以提高“可读性”是存储为一个数组。

{
"testCases" :
{
"case.1" :
{
"scenario" : "this the case 1.",
"result" : ["this is a very long line which is not easily readble.",
"so i would like to write it in multiple lines.",
"but, i do NOT require any new lines in the output."]
}
}
}


}

然后在需要的时候加入它

    result.join(" ")

不是很好的解决方案,但你可以试试 工具。它允许您在编辑器中编写多行文本,然后将其转换为适当的有效 JSON 格式。

注意: 它为新行添加了’n’字符,但是您可以在任何文本编辑器中使用“ Replace all。功能。

我相信这取决于你使用的是什么 json 解释器... ... 在普通的 javascript 中,你可以使用行结束符

{
"testCases" :
{
"case.1" :
{
"scenario" : "this the case 1.",
"result" : "this is a very long line which is not easily readble. \
so i would like to write it in multiple lines. \
but, i do NOT require any new lines in the output."
}
}
}