我有以下数据:
d = "{\"key_1": \" val_1\", \"key_2\": \"val_2\"}{\"key_3\": \" val_3\", \"key_4\": \"val_4\"}"
我想翻译成字典列表,例如
d_list = [{\"key_1": \" val_1\", \"key_2\": \"val_2\"}, {\"key_3\": \" val_3\", \"key_4\": \"val_4\"}]
json.loads(d)给我以下类型的错误:提高ValueError(errmsg(“额外数据”,s,结尾,len(s)))
有什么建议么?
最佳答案
您可以使用JSONDecoder
及其raw_decode()
方法来完成此操作。 raw_decode()
将读取一个完整的JSON对象,并返回一个元组,其第一个成员是该对象,其第二个是解码器停止读取的字符串的偏移量。
基本上,您需要读取一个对象,然后将其存储在数组中,然后从字符串中读取下一个对象,依此类推,直到到达字符串末尾。像这样:
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)))
将输出以下内容:
[{"key_1": " val_1", "key_2": "val_2"}, {"key_4": "val_4", "key_3": " val_3"}]
关于python - Json有多个字典,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11765734/