简体   繁体   English

JSON 是否允许多行字符串?

[英]Are multi-line strings allowed in JSON?

Is it possible to have multi-line strings in JSON? JSON中是否可以有多行字符串?

It's mostly for visual comfort so I suppose I can just turn word wrap on in my editor, but I'm just kinda curious.这主要是为了视觉上的舒适,所以我想我可以在我的编辑器中打开自动换行,但我只是有点好奇。

I'm writing some data files in JSON format and would like to have some really long string values split over multiple lines.我正在以 JSON 格式编写一些数据文件,并希望将一些非常长的字符串值分成多行。 Using python's JSON module I get a whole lot of errors, whether I use \ or \n as an escape.使用 python 的 JSON 模块,无论我使用\还是\n作为转义符,我都会遇到很多错误。

JSON does not allow real line-breaks. JSON不允许真正的换行符。 You need to replace all the line breaks with \\n .您需要用\\n替换所有换行符。

eg:例如:

"first line second line"

can saved with:可以保存:

"first line\\nsecond line"

Note:笔记:

for Python , this should be written as:对于Python ,这应该写成:

"first line\\\\nsecond line"

where \\\\ is for escaping the backslash, otherwise python will treat \\n as the control character "new line"其中\\\\用于转义反斜杠,否则 python 会将\\n视为控制字符“换行”

I have had to do this for a small Node.js project and found this work-around :我不得不为一个小型 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>"

 ],
}

This looks quite neat to me, appart from that I have to use double quotes everywhere.这对我来说看起来很整洁,除此之外我必须在任何地方使用双引号。 Though otherwise, I could, perhaps, use YAML, but that has other pitfalls and is not supported natively.否则,我也许可以使用 YAML,但它还有其他缺陷,并且不受本机支持。 Once parsed, I just use myData.modify_head.join('\\n') or myData.modify_head.join() , depending upon whether I want a line break after each string or not.解析后,我只使用myData.modify_head.join('\\n')myData.modify_head.join() ,具体取决于我是否想要在每个字符串后换行。

Unfortunately many of the answers here address the question of how to put a newline character in the string data.不幸的是,这里的许多答案解决了如何在字符串数据中放置换行符的问题。 The question is how to make the code look nicer by splitting the string value across multiple lines of code.问题是如何通过将字符串值拆分为多行代码来使代码看起来更好。 (And even the answers that recognize this provide "solutions" that assume one is free to change the data representation, which in many cases one is not.) (甚至承认这一点的答案也提供了“解决方案”,假设人们可以自由地更改数据表示,而在许多情况下却不是这样。)

And the worse news is, there is no good answer.更糟糕的消息是,没有好的答案。

In many programming languages, even if they don't explicitly support splitting strings across lines, you can still use string concatenation to get the desired effect;在很多编程语言中,即使它们不明确支持跨行拆分字符串,您仍然可以使用字符串连接来获得所需的效果; and as long as the compiler isn't awful this is fine.只要编译器不是很糟糕,就可以了。

But json is not a programming language;但是 json 不是一种编程语言; it's just a data representation.它只是一个数据表示。 You can't tell it to concatenate strings.你不能告诉它连接字符串。 Nor does its (fairly small) grammar include any facility for representing a string on multiple lines.它的(相当小的)语法也不包括用于在多行上表示字符串的任何工具。

Short of devising a pre-processor of some kind (and I, for one, don't feel like effectively making up my own language to solve this issue), there isn't a general solution to this problem.没有设计某种预处理器(对于一个人来说,我不想有效地编写自己的语言来解决这个问题),这个问题没有通用的解决方案。 IF you can change the data format, then you can substitute an array of strings.如果您可以更改数据格式,那么您可以替换一个字符串数组。 Otherwise, this is one of the numerous ways that json isn't designed for human-readability.否则,这是 json 不是为人类可读性而设计的众多方式之一。

Check out the specification !查看规格 The JSON grammar's char production can take the following values: JSON 语法的char生成可以采用以下值:

  • any-Unicode-character-except- " -or- \\ -or-control-character any-Unicode-character-except- " -or- \\ -or-control-character
  • \\"
  • \\\\
  • \\/
  • \\b
  • \\f
  • \\n
  • \\r
  • \\t
  • \\u\u003c/code> four-hex-digits \\u\u003c/code>四位十六进制数字

Newlines are "control characters" so, no, you may not have a literal newline within your string.换行符是“控制字符”,因此,不,您的字符串中可能没有文字换行符。 However you may encode it using whatever combination of \\n and \\r you require.但是,您可以使用所需的\\n\\r任何组合对其进行编码。

JSON doesn't allow breaking lines for readability. JSON 不允许为了可读性而换行。

Your best bet is to use an IDE that will line-wrap for you.你最好的选择是使用一个可以为你换行的 IDE。

This is a really old question, but I came across this on a search and I think I know the source of your problem.这是一个非常古老的问题,但我在搜索中遇到了这个问题,我想我知道您的问题的根源。

JSON does not allow "real" newlines in its data; JSON 不允许在其数据中使用“真正的”换行符; it can only have escaped newlines.它只能转义换行符。 See the answer from @YOU .请参阅@YOU答案 According to the question, it looks like you attempted to escape line breaks in Python two ways: by using the line continuation character ( "\\" ) or by using "\\n" as an escape.根据问题,您似乎试图通过两种方式在 Python 中转义换行符:使用行继续符 ( "\\" ) 或使用"\\n"作为转义符。

But keep in mind: if you are using a string in python, special escaped characters ( "\\t" , "\\n" ) are translated into REAL control characters!但请记住:如果您在 python 中使用字符串,特殊的转义字符( "\\t""\\n" )会被转换为真正的控制字符! The "\\n" will be replaced with the ASCII control character representing a newline character, which is precisely the character that is illegal in JSON. "\\n"将被替换为代表换行符的 ASCII 控制字符,这正是 JSON 中的非法字符。 (As for the line continuation character, it simply takes the newline out.) (至于换行符,它只是简单地取出换行符。)

So what you need to do is to prevent Python from escaping characters.所以你需要做的是防止Python对字符进行转义。 You can do this by using a raw string (put r in front of the string, as in r"abc\\ndef" , or by including an extra slash in front of the newline ( "abc\\\\ndef" ).您可以通过使用原始字符串(将r放在字符串前面,如r"abc\\ndef" ,或通过在换行符 ( "abc\\\\ndef" ) 前面包含一个额外的斜杠来执行此操作。

Both of the above will, instead of replacing "\\n" with the real newline ASCII control character, will leave "\\n" as two literal characters, which then JSON can interpret as a newline escape.上述两种意志,而不是取代的"\\n"与真实换行符ASCII控制字符,会留下"\\n"两个文字字符,然后JSON可以解释为一个换行符逃逸。

Write property value as a array of strings.将属性值写为字符串数组。 Like example given over here https://gun.io/blog/multi-line-strings-in-json/ .就像这里给出的例子https://gun.io/blog/multi-line-strings-in-json/ This will help.这会有所帮助。

We can always use array of strings for multiline strings like following.我们总是可以将字符串数组用于多行字符串,如下所示。

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

And we can easily iterate array to display content in multi line fashion.我们可以轻松地迭代数组以多行方式显示内容。

Is it possible to have multi-line strings in JSON? 是否可以在JSON中使用多行字符串?

Yes. 是。 I just tested this now with my Firefox web browser by pressing F12, clicking console and typing at the bottom of the screen. 我刚刚使用我的Firefox网络浏览器测试了这一点,按F12,点击控制台并在屏幕底部输入。

x={text:"hello\nworld"}

Object x has just been created from a JSON format string containing a multi-line string. 对象x刚刚从包含多行字符串的JSON格式字符串创建。

console.log(x.text)
hello
world

x.text is displayed showing that it is a multi-line string. 显示x.text,显示它是一个多行字符串。

These two tests show that Firefox's Javascript interpreter is happy to create and use JSON with multiline strings. 这两个测试表明,Firefox的Javascript解释器很乐意使用多行字符串创建和使用JSON。

More tests with JSON.stringify and JSON.parse showed the Javascript interpreter can convert an object containing multiline strings to JSON and parse it back again with no problem at all. 使用JSON.stringifyJSON.parse进行的更多测试表明,Javascript解释器可以将包含多行字符串的对象转换为JSON并再次解析它,完全没有任何问题。

I have in the past stored the complete works of Shakespeare as a property in a JSON object and then sent it over the internet, uncorrupted. 我过去将莎士比亚的全部作品存储为JSON对象中的属性,然后通过互联网发送,没有损坏。

Example

Here is a two line string entered over three lines 这是通过三行输入的两行字符串

x={text:"expert\
s\nex\
change"}

We can display the object 我们可以显示对象

console.log(x)

giving

Object { text: "experts\nexchange" }

or the string 或者字符串

console.log(x.text)

giving

experts
exchange

The end of lines in the string result from using \\n and the multiple input lines are achieved using just \\ at the end of the line. 字符串中的行结束来自使用\\ n,并且在行的末尾仅使用\\来实现多个输入行。

In practice you might want to synchronize your line endings with the ones in the string, eg 实际上,您可能希望将行结尾与字符串中的行结尾同步,例如

x={text:"experts\n\
exchange"}

Multi-Line String Length 多行字符串长度

console.log("Hello\nWorld".length)
11 
console.log("Hello World".length)
11

Note that the string with the newline is not longer than the string with the space. 请注意,带换行符的字符串不长于带空格的字符串。 Even though two characters were typed on the keyboard ('\\' and 'n'), only one character is stored in the string. 即使键盘上键入了两个字符('\\'和'n'),字符串中也只存储一个字符。

Use regex to replace all occurrences of \\r\\n with \\\\n . 使用正则表达式将所有出现的\\r\\n替换为\\\\n

This worked for me in scala. 这在scala中对我有用。

val newstr = str.replace("\r\n", "\\n")

Use json5 (loader) see https://json5.org/ - example (by json5) 使用json5(loader)参见https://json5.org/ - example(by json5)

{
  lineBreaks: "Look, Mom! \
No \\n's!",
}

If you are willing to use Node.js, you can do this: 如果您愿意使用Node.js,您可以这样做:

module.exports = {

  multilineStr: `

     dis my life 
     it's now or never

  `

}

you can import with Node.js and convert it to JSON easily like so: 您可以使用Node.js导入并轻松将其转换为JSON:

echo `node -pe 'JSON.stringify(require("./json-mod.js"))'`

and you get: 你得到:

{"multilineStr":"\n \n dis my life\n it's now or never\n \n "}

how it works : you use Node.js to load a JS module, which creates a JS object which can easily be JSON stringified by Node.js. 它是如何工作的 :你使用Node.js加载一个JS模块,它创建一个JS对象,可以很容易地被Node.js字符串化。 The -e option evaluates the string, and the -p option echoes the return result of the last Node.js operation to stdout. -e选项评估字符串, -p选项将最后一个Node.js操作的返回结果回显到stdout。

If you want to load a .js script that's in a different working directory, you have to switch the "" and '' strings: 如果要加载位于不同工作目录中的.js脚本,则必须切换“”和“”字符串:

my_script='../json-mod.js'
echo `node -pe "JSON.stringify(require('$my_script'))"`

While not standard, I found that some of the JSON libraries have options to support multiline Strings.虽然不是标准的,但我发现一些 JSON 库有支持多行字符串的选项。 I am saying this with the caveat, that this will hurt your interoperability.我在说这句话时要注意,这会损害您的互操作性。

However in the specific scenario I ran into, I needed to make a config file that was only ever used by one system readable and manageable by humans.然而,在我遇到的特定场景中,我需要制作一个只能由一个系统使用的配置文件,该文件可供人类阅读和管理。 And opted for this solution in the end.并最终选择了这个解决方案。

Here is how this works out on Java with Jackson :以下是使用Jackson在 Java 上的工作方式:

JsonMapper mapper = JsonMapper.builder()
   .enable(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS)
   .build()

Try this, it also handles the single quote which is failed to parse by JSON.parse() method and also supports the UTF-8 character code.试试这个,它还可以处理 JSON.parse() 方法解析失败的单引号,并且还支持 UTF-8 字符代码。

    parseJSON = function() {
        var data = {};
        var reader = new FileReader();
        reader.onload = function() {
            try {
                data = JSON.parse(reader.result.replace(/'/g, "\""));
            } catch (ex) {
                console.log('error' + ex);
            }
        };
        reader.readAsText(fileSelector_test[0].files[0], 'utf-8');
}

Use an array of strings:使用字符串数组:

{
    "text": [
"line 1 line 1 line 1 line 1 line 1 line 1 line 1 line 1 ",
"line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2"
     ]
}

then join them in code:然后在代码中加入它们:

<your JSON object>.text.join()

You can encode and decode xml strings您可以对 xml 字符串进行编码和解码

{
  "xml": "PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiID8+CiAgPFN0cnVjdHVyZXM+CiAgICAgICA8aW5wdXRzPgogICAgICAgICAgICAgICAjIFRoaXMgcHJvZ3JhbSBhZGRzIHR3byBudW1iZXJzCgogICAgICAgICAgICAgICBudW0xID0gMS41CiAgICAgICAgICAgICAgIG51bTIgPSA2LjMKCiAgICAgICAgICAgICAgICMgQWRkIHR3byBudW1iZXJzCiAgICAgICAgICAgICAgIHN1bSA9IG51bTEgKyBudW0yCgogICAgICAgICAgICAgICAjIERpc3BsYXkgdGhlIHN1bQogICAgICAgICAgICAgICBwcmludCgnVGhlIHN1bSBvZiB7MH0gYW5kIHsxfSBpcyB7Mn0nLmZvcm1hdChudW0xLCBudW0yLCBzdW0pKQogICAgICAgPC9pbnB1dHM+CiAgPC9TdHJ1Y3R1cmVzPg=="
}

then decode it on server side然后在服务器端解码

public class XMLInput
{
        public string xml { get; set; }
        public string DecodeBase64()
        {
            var valueBytes = System.Convert.FromBase64String(this.xml);
            return Encoding.UTF8.GetString(valueBytes);
        }
}

public async Task<string> PublishXMLAsync([FromBody] XMLInput xmlInput)
{
     string data = xmlInput.DecodeBase64();
}

once decoded you'll get your original xml解码后,您将获得原始 xml

<?xml version="1.0" encoding="utf-8" ?>
  <Structures>
       <inputs>
               # This program adds two numbers

               num1 = 1.5
               num2 = 6.3

               # Add two numbers
               sum = num1 + num2

               # Display the sum
               print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
       </inputs>
  </Structures>

\n\r\n worked for me !! \n\r\n为我工作!

\n for single line break and \n\r\n for double line break \n表示单行换行, \n\r\n表示双行换行

I see many answers here that may not works in most cases but may be the easiest solution if let's say you wanna output what you wrote down inside a JSON file (for example: for language translations where you wanna have just one key with more than 1 line outputted on the client) can be just adding some special characters of your choice PS: allowed by the JSON files like \\ before the new line and use some JS to parse the text... like:我在这里看到许多答案在大多数情况下可能不起作用,但如果假设你想要 output 你在 JSON 文件中写下的内容,这可能是最简单的解决方案(例如:对于语言翻译,你只想拥有一个键超过 1客户端上输出的行)可以只添加一些您选择的特殊字符PS:JSON 文件允许在新行之前像\\并使用一些 JS 来解析文本...例如:

Example:例子:

File (text.json)文件(文本.json)

{"text": "some JSON text. \\ Next line of JSON text"}

import text from 'text.json'
{text.split('\\')
.map(line => {
return (
   <div>
     {line}
     <br />
   </div>
     );
})}}

This is a very old question, but I had the same question when I wanted to improve readability of our Vega JSON Specification code which uses complex conditoinal expressions.这是一个非常古老的问题,但当我想提高使用复杂条件表达式的 Vega JSON 规范代码的可读性时,我遇到了同样的问题。 The code is like this .代码是这样的。

As this answer says, JSON is not designed for human.正如这个答案所说, JSON 不是为人类设计的。 I understand that is a historical decision and it makes sense for data exchange purposes.我知道这是一个历史性的决定,对于数据交换目的来说是有意义的。 However, JSON is still used as source code for such cases.但是,JSON 仍然用作此类案例的源代码。 So I asked our engineers to use Hjson for source code and process it to JSON.于是就让我们的工程师对源码使用Hjson ,处理成JSON。

For example, in Git for Windows environment, you can download the Hjson cli binary and put it in git/bin directory to use.比如Git为Windows环境,可以下载Hjson cli binary,放到git/bin目录下使用。 Then, convert (transpile) Hjson source to JSON. To use automation tools such as Make will be useful to generate JSON.然后,将Hjson源转换(transpile)为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."
}

In case of using the transformed JSON in programming languages, language-specific libraries like hjson-js will be useful.如果在编程语言中使用转换后的 JSON,特定语言的库(如hjson-js)将很有用。

I noticed the same idea was posted in a duplicated question but I would share a bit more information.我注意到在重复的问题中发布了相同的想法,但我会分享更多信息。

Assuming the question has to do with easily editing text files and then manually converting them to json, there are two solutions I found:假设问题与轻松编辑文本文件然后手动将它们转换为 json 有关,我找到了两个解决方案:

  1. 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 . hjson (在之前的回答中提到过),在这种情况下,您可以通过执行hjson source.json > target.hjson将现有的 json 文件转换为 hjson 格式,在您喜欢的编辑器中进行编辑,然后转换回 json hjson -j target.hjson > source.json You can download the binary here or use the online conversion here .您可以在此处下载二进制文件或此处使用在线转换。
  2. jso.net , which does the same, but with a slightly different format (single and double quoted strings are simply allowed to span multiple lines). jso.net ,它的作用相同,但格式略有不同(单引号和双引号字符串只允许跨越多行)。 Conveniently, the homepage has editable input fields so you can simply insert your multiple line json/jso.net files there and they will be converted online to standard json immediately.方便的是,主页有可编辑的输入字段,因此您只需在那里插入多行 json/jso.net 文件,它们将立即在线转换为标准 json。 Note that jso.net supports much more goodies for templating json files, so it may be useful to look into, depending on your needs.请注意,jso.net 支持更多用于模板化 json 文件的好东西,因此根据您的需要查看它可能会有用。

Try using base64 encoded string value. 尝试使用base64编码的字符串值。 Worked for me most of the time. 大部分时间都在为我工作。

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

after base64 encoded string look like base64编码后的字符串看起来像

{
    "singleLine": "Some singleline String",
    "multiline": "TGluZSBvbmUKTGluZSBUd28KTGluZSBUaHJlZQ=="
} 

base64 encoding and decoding is available in all languages. base64编码和解码以所有语言提供。

If it's just for presentation in your editor you may use ` instead of " or '如果它只是为了在您的编辑器中展示,您可以使用 ` 而不是 " 或 '

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. 
`
}

Examples:例子:

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

will put in console:将放入控制台:
First line Second line第一行 第二行

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

will put in console:将放入控制台:
First line第一行
second line第二行

Hope this answered your question.希望这回答了你的问题。

put the multiline text on txt file and then 将多行文本放在txt文件上然后

var str = {
    text: cat('path_to_file/text.txt')
}

(it work's on mongoDB) (它在mongoDB上运行)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM