将多个 JSON 字典 List 组合成一个字典

Combine multiple JSON dictionary List into single dictionary

我在 out.json 文件

中有以下几行
{"rl": {"entries": [{"value": {"query": "4c20a3718c3cfcc2cd418a25a020e608"}, "status": "KNOWN"}, {"value": {"query": "af6c05f057c80944a88c014c1c081c83e2e9"}, "status": "KNOWN"}]}}
{"rl": {"entries": [{"value": {"query": "fb0e8c7d856e7e5c99c339d593f26aa9b"}, "status": "KNOWN"}, {"value": {"query": "49d9890de7e394f3549510fdeafa888"}, "status": "KNOWN"}]}}
{"rl": {"entries": [{"value": {"query": "bf2f9b6c00432a54e229c75e2b13bb"}, "status": "SUSPICIOUS"}, {"value": {"query": "b7cb4b620854f2b0d5dfe86ffd9ab"}, "status": "KNOWN"}, {"value": {"query": "9b4e2465b2da99097899662eec2b"}, "status": "KNOWN"}]}}

现在,我想将所有字典列表合并到单个文件中的一个列表中,如下面的一组代码:

{"rl": {"entries": [{"value": {"query": "fb0e8c7d856e7e5c99c339d593f26aa9b"}, "status": "KNOWN"}, {"value": {"query": "bf2f9b6c00432a54e229c75e2b13bb"}, "status": "SUSPICIOUS"}, {"value": {"query": "9b4e2465b2da99097899662eec2b"}, "status": "KNOWN"}, {"value": {"query": "4c20a3718c3cfcc2cd418a25a020e608"}, "status": "KNOWN"}, {"value": {"query": "b7cb4b620854f2b0d5dfe86ffd9ab"}, "status": "KNOWN"}, {"value": {"query": "49d9890de7e394f3549510fdeafa888"}, "status": "KNOWN"}, {"value": {"query": "af6c05f057c80944a88c014c1c081c83e2e9"}, "status": "KNOWN"}]}}

需要解析out.json,其中包含相同结构的字典列表,需要输出成单组列表。

你可以试试

from ast import literal_eval

with open(file_path) as f:
    dict_ls  = [literal_eval(i) for i in f.readlines()]
combine_list = []
res_dict = {}
for i in dict_ls:
    for k, v in i.items():
        if not isinstance(v, list):
            res_dict[k] = {list(v.keys())[0]: combine_list}
            dict_ls.append(v)
        else:
            combine_list.extend(v)
print(res_dict)

这将输出

{'rl': {'entries': [{'value': {'query': '4c20a3718c3cfcc2cd418a25a020e608'}, 'status': 'KNOWN'}, {'value': {'query': 'af6c05f057c80944a88c014c1c081c83e2e9'}, 'status': 'KNOWN'}, {'value': {'query': 'fb0e8c7d856e7e5c99c339d593f26aa9b'}, 'status': 'KNOWN'}, {'value': {'query': '49d9890de7e394f3549510fdeafa888'}, 'status': 'KNOWN'}, {'value': {'query': 'bf2f9b6c00432a54e229c75e2b13bb'}, 'status': 'SUSPICIOUS'}, {'value': {'query': 'b7cb4b620854f2b0d5dfe86ffd9ab'}, 'status': 'KNOWN'}, {'value': {'query': '9b4e2465b2da99097899662eec2b'}, 'status': 'KNOWN'}]}}

首先需要通过literal_eval方法将文件中的每一行转换为字典。
然后此代码将 运行 遍历 dict_ls 列表中的每个字典,并将所有列表值获取到组合列表中,并将在 res_dict 中创建在每个字典键中找到的所有键。