我在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,它包含与字典列表相同的结构,需要输出到单个列表集中。
答案 0 :(得分:1)
您可以尝试
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
中创建每个字典键中找到的所有键。