Json有多个词典

Ghe*_*hen 1 python json dictionary

我有以下数据:

d = "{\"key_1": \" val_1\", \"key_2\": \"val_2\"}{\"key_3\": \" val_3\", \"key_4\": \"val_4\"}"
Run Code Online (Sandbox Code Playgroud)

我想将其翻译成字典列表,例如

d_list = [{\"key_1": \" val_1\", \"key_2\": \"val_2\"}, {\"key_3\": \" val_3\", \"key_4\": \"val_4\"}]
Run Code Online (Sandbox Code Playgroud)
  1. json.loads(d)给出了类型错误:raise ValueError(errmsg("Extra data",s,end,len(s)))

有什么建议?

cdh*_*wie 5

您可以使用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)))
Run Code Online (Sandbox Code Playgroud)

哪个会输出这个:

[{"key_1": " val_1", "key_2": "val_2"}, {"key_4": "val_4", "key_3": " val_3"}]
Run Code Online (Sandbox Code Playgroud)