Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I put the anchor to its item with python ruamel.yaml?

I have this format YAML file,

A: true
B:
- &C
  tag1: value1
  tag2: value2
- &D
  tag1: value3
  tag2: value4

I want to convert it to the format below, add name field with anchor.

A: true
B:
- &C
  tag1: value1
  tag2: value2
  name: C
- &D
  tag1: value3
  tag2: value4
  name: D

I am not sure if it's possible. How can I do this?

like image 503
Claire Avatar asked Sep 20 '25 08:09

Claire


1 Answers

The anchor information is stored in the anchor attribute, it has a field value which you should read, and a field always_dump which you will need to set if you want the anchors to appear without any aliases referring to them:

import sys
import ruamel.yaml

yaml_str = """\
A: true
B:
- &C
  tag1: value1
  tag2: value2
- &D
  tag1: value3
  tag2: value4
"""

yaml = ruamel.yaml.YAML()
# yaml.indent(mapping=4, sequence=4, offset=2)
# yaml.preserve_quotes = True
data = yaml.load(yaml_str)
for mapping in data['B']:
    mapping['name'] = mapping.anchor.value
    mapping.anchor.always_dump = True
yaml.dump(data, sys.stdout)

which gives:

A: true
B:
- &C
  tag1: value1
  tag2: value2
  name: C
- &D
  tag1: value3
  tag2: value4
  name: D

If you don't know where the anchors might show up in your data structure, you'll have to recursively walk the values of dicts and elements of lists to do the above.

like image 118
Anthon Avatar answered Sep 22 '25 21:09

Anthon