如何将长 JSON 值字符串编码为多行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21077104/
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
How to code long JSON value strings as multiline?
提问by Paul
IMPORTANT:I am not asking about renderingstrings as multiline.
重要提示:我不是在问将字符串渲染为多行。
I am talking about splitting a long string in a JSON into multiple lines in my source codewhen this string should logically be on a single line.
我正在谈论将 JSON 中的长字符串拆分为源代码中的多行,而该字符串在逻辑上应该位于一行上。
In short: I want source line breaking rules similar to HTML.
简而言之:我想要类似于 HTML 的源代码换行规则。
{
"id": 550,
"text": "this is long text "
"very-very-very long text "
"longer than you can imagine."
}
This text should be rendered as:
此文本应呈现为:
this is long text very-very-very long text longer than you can imagine.
The JSON is being referenced in JavaScript.
JSON 正在被 JavaScript 引用。
This is not a duplicate of Multiline strings in JSONbecause this question strongly refers to JavaScript and that question has no clear accepted answer.
采纳答案by Pinal
You can use multiple lines string representation in javascript:
您可以在 javascript 中使用多行字符串表示:
JSON.parse('{"a" : "a\
asd"}')
Tried in console. It works.
在控制台中尝试过。有用。
回答by mjkaufer
According to JSONLint.com, the following multiline JSON is valid. So in short, yes, you can hit enter and break it into different lines.
根据 JSONLint.com,以下多行 JSON 是有效的。简而言之,是的,您可以按 Enter 键并将其分成不同的行。
{
"a": 10,
"b": 12,
"c": 19
}
EDIT: I think I misread your question. I don't think you're able to break between a string like below. That does not work.
编辑:我想我误读了你的问题。我认为您无法在如下所示的字符串之间断开。那行不通。
{
"a": "abcde
fg",
"b": 12,
"c": 19
}
回答by Jose Moreno
You can't do it, you need to write the value in one line, if you want write in the next row, you need to put \n in your code
你不能这样做,你需要把值写在一行,如果你想写在下一行,你需要把\n放在你的代码中

