Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing YAML, return with line number

Tags:

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.

like image 457
puzzlet Avatar asked Nov 10 '12 03:11

puzzlet


1 Answers

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) 
like image 184
augurar Avatar answered Sep 23 '22 11:09

augurar