JSON值是否可以包含多行字符串

use*_*155 101 json multiline

我正在编写一个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"
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

Lig*_*ica 55

查看规格!JSON语法的char生成可以采用以下值:

  • any-Unicode-character-except- "-or- \-or-control-character
  • \"
  • \\
  • \/
  • \b
  • \f
  • \n
  • \r
  • \t
  • \u 四十六进制数字

换行符是"控制字符",所以不,你的字符串中可能没有文字换行符.然而,你可以使用任何的组合进行编码,\n并且\r您需要.

JSONLint工具确认您的JSON是无效的.


更新:如果你想在你的JSON语法中写入换行符而不在数据中实际包含换行符,那么你甚至会失败.虽然JSON旨在在某种程度上对人类友好,但它仍然是数据,并且您正在尝试对该数据应用任意格式.这绝对不是JSON的意思.


Bri*_*ffe 27

我不确定您的确切要求,但提高"可读性"的一种可能解决方案是将其存储为数组.

{
  "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."]
    }
  }
}

}
Run Code Online (Sandbox Code Playgroud)

在需要时再次加入

result.join(" ")
Run Code Online (Sandbox Code Playgroud)

  • 但这是无意义的.这是一个抽象泄漏.我认为以这种方式指定的数据格式基本上是破碎的. (9认同)
  • 我无法想象以这种方式设计API或JSON文档只是为了增加字符串的可读性(仅用于我猜的调试原因):| .... (3认同)

Cod*_*key 8

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

注意:它为新行添加了 '\n' 字符,但您可以在任何文本编辑器中使用“全部替换..”功能简单地删除它们。