如何在YAML中引用别名贴图值
我觉得这是不可能的,但我有一个YAML片段,看起来如下所示:如何在YAML中引用别名贴图值,yaml,Yaml,我觉得这是不可能的,但我有一个YAML片段,看起来如下所示: .map_values: &my_map a: 'D' b: 'E' a: 'F' section: stage: *my_map['b'] 我希望stage的值为E 这在YAML中是可能的吗?我已经尝试了我所能想到的每一种替代的化身。因为在映射中有一个重复的键,这是不允许的 在YAML 1.2中(至少应该在YAML 1.1中发出警告),这是 不去工作,但即使你纠正了,你也不能那样做 只有锚和别名 YAML
.map_values: &my_map
a: 'D'
b: 'E'
a: 'F'
section:
stage: *my_map['b']
我希望stage
的值为E
这在YAML中是可能的吗?我已经尝试了我所能想到的每一种替代的化身。因为在映射中有一个重复的键,这是不允许的 在YAML 1.2中(至少应该在YAML 1.1中发出警告),这是 不去工作,但即使你纠正了,你也不能那样做 只有锚和别名 YAML中唯一可用的类似替代品的替代品是。这在YAML规范中是间接引用的,不包括在其中,但在大多数解析器中都可用
唯一允许它做的事情是使用一个或多个其他映射的键值对“更新”映射,如果映射中不存在该键。您使用的特殊键是:*我的地图应该是
@FiboKowalsky,实际上应该是
.map_values: &my_map
a: D
b: E
c: F
section: !Lookup
- *my_map
- stage: <b>
.map_values: &my_map
a: D
b: E
c: F
section: !Lookup
<<: *my_map
stage: <b>
import sys
import ruamel.yaml
from pathlib import Path
input = Path('input.yaml')
yaml = ruamel.yaml.YAML(typ='safe')
yaml.default_flow_style = False
@yaml.register_class
class Lookup:
@classmethod
def from_yaml(cls, constructor, node):
"""
this expects a two entry sequence, in which the first is a mapping X, typically using
an alias
the second entry should be an mapping, for which the values which have the form <key>
are looked up in X
non-existing keys will throw an error during loading.
"""
X, res = constructor.construct_sequence(node, deep=True)
yield res
for key, value in res.items():
try:
if value.startswith('<') and value.endswith('>'):
res[key] = X[value[1:-1]]
except AttributeError:
pass
return res
data = yaml.load(input)
yaml.dump(data, sys.stdout)
.map_values:
a: D
b: E
c: F
section:
stage: E