Reputation: 381
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\"}]
Any suggestions?
Upvotes: 1
Views: 4190
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
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
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