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.
Here's an improved version of puzzlet's answer:
import yaml from yaml.loader import SafeLoader class SafeLineLoader(SafeLoader): def construct_mapping(self, node, deep=False): mapping = super(SafeLineLoader, self).construct_mapping(node, deep=deep) # Add 1 so line numbering starts at 1 mapping['__line__'] = node.start_mark.line + 1 return mapping
You can use it like this:
data = yaml.load(whatever, Loader=SafeLineLoader)
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