I'm making a document generator from YAML data, which would specify which line of the YAML file each item is generated from. What is the best way to do this? So if the YAML file is like this:
- key1: item 1
key2: item 2
- key1: another item 1
key2: another item 2
I want something like this:
[
{'__line__': 1, 'key1': 'item 1', 'key2': 'item 2'},
{'__line__': 3, 'key1': 'another item 1', 'key2': 'another item 2'},
]
I'm currently using PyYAML, but any other library is OK if I can use it from Python.
If you are using ruamel.yaml >= 0.9 (of which I am the author), and use the
RoundTripLoader
, you can access the propertylc
on collection items to get line and column where they started in the source YAML:(line and column start counting at 0).
This answer show how to add the
lc
attribute to string types during loading.Here's an improved version of puzzlet's answer:
You can use it like this:
I've made it by adding hooks to
Composer.compose_node
andConstructor.construct_mapping
: