Bas Bas - 1 year ago 73
Python Question

Python: String [ [k1:v1, k2:v2], [k3:v3] ] to Object

I'm stuck with an application that outputs the following

[[_type:logs, _id:AVY0ofxOHiyEPsw_vkZS, _index:firewall-all-2016.07.29, _score:13.445344], [_type:logs, _id:AVY1EI1z79siNC3TEi7P, _index:firewall-all-2016.07.29, _score:13.445344]]

I would like to parse this text into an iterable object. But the standards approach using
doesn't like the input.

Is there something else I can try before I start looking into str replace etc...

Thank you

Answer Source

How about this:

import re

data = "[[_type:logs, _id:AVY0ofxOHiyEPsw_vkZS, _index:firewall-all-2016.07.29, _score:13.445344], [_type:logs, _id:AVY1EI1z79siNC3TEi7P, _index:firewall-all-2016.07.29, _score:13.445344]]"

parsed_1 = re.findall("\[(.*?)\]", data[1:-1])

parsed_list = []
for line in parsed_1:
    parsed_dict = {}
    for record in line.split(","):
        k, v = record.split(":")
        parsed_dict[k] = v


The output is list of dictionaries, you can itarate over it in many ways.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download