Parsing key-value log in Python
<p>I have a system log that looks like the following:</p>

<pre><code>{
    a = 1
    b = 2
    c = [
            x:1,
            y:2,
            z:3,
        ]
    d = 4
}
</code></pre>

<p>I want to parse this in Python into a dictionary object with = splitting key-value pairs. At the same time, the array that is enclosed by [] is also preserved. I want to keep this as generic as possible so the parsing can also hold some future variations.</p>

<p>What I tried so far (code will be written): split each line by "=" into key-value pair, determine where [ and ] starts and end and then split the lines in between by ":" into key-value pairs. That seems a little hard-coded.. Any better idea?</p>

<p>There is probably a better answer, but I would take advantage of all your dictionary keys being at the same indentation level. There's not an obvious way to be to do this with newline splitting, JSON loading, or that sort of thing since the list structure is a bit weird (it seems like a cross between a list and a dictionary).</p>

<p>Here's an implementation that parses keys based on indentation level:</p>

<pre><code>import re

log = '''{
    a = 1
    b = 2
    c = [
            x:1,
            y:2,
            z:3,
        ]
    d = 4
}'''
log_lines = log.split('\n')[1:-1]  # strip bracket lines
KEY_REGEX = re.compile(r'    [^ ]')

d = {}
current_pair = ''
for i, line in enumerate(log_lines):
    if KEY_REGEX.match(line):
        if current_pair:
            key, value = current_pair.split('=')
            d[key.strip()] = value.strip()
        current_pair = line
    else:
        current_pair += line.strip()

if current_pair:
    key, value = current_pair.split('=')
    d[key.strip()] = value.strip()

print(d)
</code></pre>

<p><strong>Output</strong>:</p>

<pre><code>{'d': '4', 'c': '[x:1,y:2,z:3,]', 'a': '1', 'b': '2'}
</code></pre>

python