Grammar file for key=value pairs

74 Views Asked by At

I’m attempting to define a grammar file that parses the following:

Section0:
  Key0 = “Val0”
  Key1 = “Val1”
…

My attempts thus far have just resulted in one long concatenation string with no real ability to split.

Section0:
  (var=ID ‘=‘ String)*

I’m looking to have a list of dictionary-like objects.

1

There are 1 best solutions below

0
On

Here is a possible solution:

from textx import metamodel_from_str

model = r'''
Section0:
  Key0 = "Val0"
  Key1 = "Val1"
'''

grammar = r'''
Section: name=ID ':' pairs+=Pair;
Pair: name=ID '=' value=STRING;
'''

mm = metamodel_from_str(grammar)

# Define an object processor to transform each Section object
def section_processor(section):
    section.pairs = {pair.name: pair.value for pair in section.pairs}

# Register Section processor
mm.register_obj_processors({'Section': section_processor})

# Parse the input
model = mm.model_from_str(model)

assert model.name == 'Section0'
assert model.pairs == {'Key0': "Val0", 'Key1': "Val1"}

By default, textX will return a list of Pair objects in pairs attribute of the Section object. But, it is easy to transform it to a dictionary by using an object processor for the section as shown above.