gpt4 book ai didi

python - 根据键将 JSON 对象转换为 JSON 对象数组 - Python 中的代码

转载 作者:行者123 更新时间:2023-11-28 21:36:04 25 4
gpt4 key购买 nike

我有一个 JSON 对象数组。示例数组如下:

[
{
"evt.category": "file",
"evt.cpu": 0,
"evt.num": 10078507,
"evt.res": "SUCCESS",
"evt.time": 1532841047277584400,
"evt.type": "read",
"fd.filename": "libnss_files.so.2",
"fd.name": "/lib/x86_64-linux-gnu/libnss_files.so.2",
"fd.num": 13,
"fd.type": "file",
"fd.uid": "1996913",
"proc.loginshellid": 19968,
"proc.name": "last",
"proc.pid": 19969,
"thread.ismain": true,
"thread.tid": 19969
},
{
"evt.buffer": "1000",
"evt.category": "file",
"evt.cpu": 0,
"evt.num": 10078564,
"evt.res": "SUCCESS",
"evt.time": 1532841047277731300,
"evt.type": "read",
"fd.filename": "loginuid",
"fd.name": "/proc/16009/loginuid",
"fd.num": 13,
"fd.type": "file",
"fd.uid": "1996913",
"proc.loginshellid": 19968,
"proc.name": "last",
"proc.pid": 19969,
"thread.ismain": true,
"thread.tid": 19969
},
{
"evt.buffer": "",
"evt.category": "file",
"evt.cpu": 0,
"evt.num": 10078566,
"evt.res": "SUCCESS",
"evt.time": 1532841047277733400,
"evt.type": "read",
"fd.filename": "loginuid",
"fd.name": "/proc/16009/loginuid",
"fd.num": 13,
"fd.type": "file",
"fd.uid": "1996913",
"proc.loginshellid": 19968,
"proc.name": "last",
"proc.pid": 19969,
"thread.ismain": true,
"thread.tid": 19969
}
]

我想重新构造这个数组,以便每个对象都转换为另一个数组,并且每个数组应该基于这些键包含 JSON 对象,例如 evt 的 JSON 对象proc 线程

我尝试了一些在线网站来做到这一点,但都不起作用。

请帮忙。

编辑:我想要的输出如下:

[
{
"evt": {
"category": "file",
"cpu": 0,
"num": 10078507,
"res": "SUCCESS",
"time": 1532841047277584400,
"type": "read"
},
"fd": {
"filename": "libnss_files.so.2",
"name": "/lib/x86_64-linux-gnu/libnss_files.so.2",
"num": 13,
"type": "file",
"uid": "1996913"
},
"proc": {
"loginshellid": 19968,
"name": "last",
"pid": 19969
},
"thread": {
"ismain": true,
"tid": 19969
}
},
{
"evt": {
"buffer": "1000",
"category": "file",
"cpu": 0,
"num": 10078564,
"res": "SUCCESS",
"time": 1532841047277731300,
"type": "read"
},
"fd": {
"filename": "loginuid",
"name": "/proc/16009/loginuid",
"num": 13,
"type": "file",
"uid": "1996913"
},
"proc": {
"loginshellid": 19968,
"name": "last",
"pid": 19969
},
"thread" : {
"ismain": true,
"tid": 19969
}
}
]

最佳答案

import json

list_of_objects = json.loads(json_string)

new_list = []
for complex_object in list_of_objects:
new_object = {}
for composite_key, value in complex_object.items():
key, subkey = composite_key.split(".")
if key not in new_object:
new_object[key] = {}
new_object[key][subkey] = value
new_list.append(new_object)

json_string = json.dumps(new_list)

关于python - 根据键将 JSON 对象转换为 JSON 对象数组 - Python 中的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51577527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com