可以在YAML中锚定字面块吗?

8 投票
1 回答
3492 浏览
提问于 2025-04-18 12:39

我正在创建几个像下面这样的文字块,并把它们放在一个列表里。

literal1: |
    line
    of 
    text and stuff

literal2: |
    ...

但是我现在搞不明白的是怎么把它们放到列表里。我想我可以用锚点和别名,但在文字块上似乎不太管用。

这样做是不行的

literal1: | &literal1
    line
    of
    text and stuff

会报错。而且我也不想为了这个去创建一个字典

literals: &literal1
    literal1: |
        ....

来让它工作。我相信有简单的方法可以做到这一点,但我就是找不到。

1 个回答

9

这就是你想要做的事情吗?

literal1: &literal1 |
    line
    of 
    text and stuff

literal2: &literal2 |
    another line
    of text and new stuff

literals:
-  *literal1
-  *literal2    

下面这个程序会输出...

['line\nof \ntext and stuff\n', 'another line\nof text and new stuff\n']

import yaml

data="""
literal1: &literal1 |
    line
    of 
    text and stuff

literal2: &literal2 |
    another line
    of text and new stuff

literals:
-  *literal1
-  *literal2    
"""

pydata = yaml.load(data)
literals = pydata [ 'literals' ]

print ( type(literals), literals )

撰写回答