python - 根据键转换 JSON 对象或 JSON 对象数组 - Python 中的代码
问题描述
我有一个 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
thread
等。
我尝试了一些在线网站来做到这一点,但都没有奏效。
请帮忙。
编辑: 我想要的输出如下:
[
{
"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)
推荐阅读
- javascript - 如何创建单个“
= group" 与现有的 " = 组”在 D3.js 中 - python - 相同的抽象语法树是否保证相同的行为?
- python - 将 Valve 数据结构转换为 JSON
- c# - 转义泛型类型参数
XML summary tag
- c# - 使用 SQLKata 在插入语句中选择语句
- javascript - 赛普拉斯调用('removeAttr','target')不起作用
- security - What are typical use cases for self-signed code certificates?
- python - How to round away from zero
- java - 为什么我在带有 JDBC 和 MySQL 的 JSP 中出现连接失败错误
- javascript - Can't call the window position object in a function