Gheghen
Gheghen

Reputation: 381

Json with multiple dictionaries

I have the following data:

d = "{\"key_1": \" val_1\", \"key_2\": \"val_2\"}{\"key_3\": \" val_3\", \"key_4\": \"val_4\"}"

which I would like to translate to a list of dictionary, e.g.

d_list = [{\"key_1": \" val_1\", \"key_2\": \"val_2\"}, {\"key_3\": \" val_3\", \"key_4\": \"val_4\"}]
  1. json.loads(d) gives me error of type: raise ValueError(errmsg("Extra data", s, end, len(s)))

Any suggestions?

Upvotes: 1

Views: 4190

Answers (3)

Berto
Berto

Reputation: 199

I also had a similar issues where i got {key1:val1, key2:val2}{key1:val1, key2:val2}. Only way i could fix it was be following:

def json_parser(msg):
    msg=msg.split("{")
    for i in msg:
        L=i.split("}")
        msg_new={}
        for j in L:
            if j:
                LL=j.split(",")
                for l in LL:
                    msg_new[string.strip(l.split(":")[0]).replace('"','')]=string.strip(l.split(":")[1]).replace('"','')
        return msg_new

where....

try:
                        data_loaded=json.loads(data)
                    except:
                        data_loaded=json_parser(str(data))

I tried many attempts but this one could handle loads of {..}{..}{..} examples.

Upvotes: 0

cdhowie
cdhowie

Reputation: 168958

You can use JSONDecoder and its raw_decode() method to accomplish this. raw_decode() will read a complete JSON object, and return a tuple whose first member is the object, and whose second is the offset into the string where the decoder stopped reading.

Basically, you need to read one object, then store it in an array, then read the next object from the string, and so on until you are at the end of the string. Like this:

import json

def read_json_objects(data):
    decoder = json.JSONDecoder()
    offset = 0

    while offset < len(data):
        item = decoder.raw_decode(data[offset:])

        yield item[0]
        offset += item[1]

d = '{"key_1": " val_1", "key_2": "val_2"}{"key_3": " val_3", "key_4": "val_4"}'

print json.dumps(list(read_json_objects(d)))

Which will output this:

[{"key_1": " val_1", "key_2": "val_2"}, {"key_4": "val_4", "key_3": " val_3"}]

Upvotes: 5

unddoch
unddoch

Reputation: 6004

That's not valid JSON, you should try adding a comma between two objects.
d = "{\"key_1": \" val_1\", \"key_2\": \"val_2\"}, {\"key_3\": \" val_3\", \"key_4\": \"val_4\"}"

Upvotes: 0

Related Questions