在 yaml 中,有多种方法可以格式化多行的长字符串。例如:
输入:
example:
string1: An example of a long string that is split across
two lines
输出(JSON):
{
"example": {
"string1": "An example of a long string that is split across two lines"
}
}
或者使用显式折叠语法:
example:
string1: >
An example of a long string that is split across
two lines
输出:
{
"example": {
"string1": "An example of a long string that is split across two lines"
}
}
或者使用文字语法:
example:
string1: |
An example of a long string that is split across
two lines
输出:
{
"example": {
"string1": "An example of a long string that is split across\ntwo lines"
}
}
在我能找到的所有示例中,似乎生成的字符串在每行之间插入了空格或换行符。但是,我想在几行中编写一个非常长的 yaml 字符串,其中不会在结果行中插入空格。这可能吗?
我的要求:
example:
string1: Oneverylongunbrokenlinethatmustnotcon
tainanyresultingwhitespaceintheoutput
期望的输出:
{
"example": {
"string1": "Oneverylongunbrokenlinethatmustnotcontainanyresultingwhitespaceintheoutput"
}
}
这样的语法存在吗?
最佳答案
您省略了双引号标量样式,这正是您所需要的:
example:
string1: "Oneverylongunbrokenlinethatmustnotcon\
tainanyresultingwhitespaceintheoutput"
双引号标量是 YAML 中唯一允许在任意位置分成多行的标量样式。这是通过转义换行符来完成的。如果您不逃避换行符,您将得到一个空格,就像大多数其他标量样式一样。
这不适用于任何其他样式,因为只有双引号标量才会处理转义序列。
关于yaml - 如何在 yaml 中将长字符串拆分为多行而不引入空格字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69223112/