我正在尝试使用几个组件模板来构建YAML文档。我正在加载它们,构建一个Python对象,然后尝试转储它们(最终保存到文件中,但此示例仅打印出来)。正如您在下面看到的,它正在打印引用和指针,而不是我期望的字符串数据。我在做什么错(或不做什么)?
这是我用来说明我的问题的示例:
import yaml
main_template = yaml.load('organization: main')
sub_template = yaml.load('''
division: development
other:
data:
- for: users
''')
users = [ 'alice', 'bob', 'kim' ]
all_user_data = dict(main_template)
user_list = []
for user in users:
tmp = dict(sub_template)
tmp['name'] = user
user_list.append(tmp)
all_user_data['users'] = user_list
print(yaml.dump(all_user_data, default_flow_style=False))
这将产生:
organization: main
users:
- division: development
name: alice
other: &id001
data:
- for: users
- division: development
name: bob
other: *id001
- division: development
name: kim
other: *id001
我期望这样的输出:
organization: main
users:
- division: development
name: alice
other:
data:
- for: users
- division: development
name: bob
other:
data:
- for: users
- division: development
name: kim
other:
data:
- for: users
答案 0 :(得分:1)
正如Anthon在Avoid references in PyYAML中建议的那样,您可以
yaml.Dumper.ignore_aliases = lambda *args : True
然后
print(yaml.dump(all_user_data, default_flow_style=False))
收益
organization: main
users:
- division: development
name: alice
other:
data:
- for: users
- division: development
name: bob
other:
data:
- for: users
- division: development
name: kim
other:
data:
- for: users
我不知道为什么会这样。感谢安通。
橄榄