I'm trying to build a YAML doc using a couple of component templates. I'm loading them, building a Python object, then trying to dump them (ultimately to a file, but this example just prints). As you can see below, it's printing references and pointers instead of the string data I'm expecting. What am I doing wrong (or not doing)?
This is an example I made to demonstrate my problem:
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))
This produces:
organization: main
users:
- division: development
name: alice
other: &id001
data:
- for: users
- division: development
name: bob
other: *id001
- division: development
name: kim
other: *id001
I'm expecting output like this:
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
As Anthon suggests in Avoid references in PyYAML, you can do
yaml.Dumper.ignore_aliases = lambda *args : True
Then,
print(yaml.dump(all_user_data, default_flow_style=False))
yields
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
I have no idea why this works. Kudos to Anthon.
Oliver
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With