Search code examples
pythonjsonparsingconfiguration-filesdata-transfer-objects

How to parse this special config file in python?


I have some config files and the data format can't be changed.

One of them looks like this:

root {
  configuration {
    field_a: "aaaa"
    field_b: "bbbb"
  }
  child {
    configuration {
        field_a: "aaa1"
        field_b: "bbb1"
    }
  }
  child {
    configuration {
        field_a: "aaa2"
        field_b: "bbb2"
    }
  }
}

What i need is to parse the file and save it as JSON objects:

{root: 
    {field_a:"aaaa",field_b:"bbbb"},
    children: [{field_a:"aaa", field_b:"bbb"}, ... ]
}

Is there any way to make it possible ?


Solution

  • A quick thought:

    if the config is well indented and lined as the example:

    replace "{" and "}" s to make it like this:

    root:
      configuration:
        field_a: "aaaa"
        field_b: "bbbb"
      child:
        configuration:
            field_a: "aaa"
            field_b: "bbb"
    

    And now it's a yaml format file! just transform from yaml to json by all means!

    import yaml
    import json
    
    s = "yamlstr"  # your yaml str
    data = yaml.load(s)
    jsondata = json.dumps(data)
    print jsondata
    

    UPDATE

    As the fact that child is a list, and both "root", "configuration" and "child" seems to be keywords, change a bit and go for the workaround:

    make this happen:

    root:
      - configuration:
        field_a: "aaaa"
        field_b: "bbbb"
      - child:
        - configuration:
            field_a: "aaa1"
            field_b: "bbb1"
      - child:
        - configuration:
            field_a: "aaa2"
            field_b: "bbb2"
    

    and output python dict would be:

    {'root': [{'configuration': None, 'field_b': 'bbbb', 'field_a': 'aaaa'}, {'child': [{'configuration': {'field_b': 'bbb1', 'field_a': 'aaa1'}}]}, {'child': [{'configuration': {'field_b': 'bbb2', 'field_a': 'aaa2'}}]}]}
    

    Now do some simple programming and make it your structure :-)