python - 在python中将json从一种形式转换为另一种形式
问题描述
我在更改列表后收到了回复。我的回复看起来像这样:
{
"response": [
{
"timestamp": "21:15-21:30",
"logs": [
{
"exception": "IllegalAgrumentsException",
"count": 1
}
]
},
{
"timestamp": "21:15-21:30",
"logs": [
{
"exception": "NullPointerException",
"count": 2
}
]
},..
我希望结果是这样的: -
"response": [
{
"timestamp": "21:15-21:30",
"logs": [
{
"exception": "IllegalAgrumentsException",
"count": 1
},
{
"exception": "NullPointerException",
"count": 2
} ]
}
如何在 python 中像上面那样将日志合并在一起?
解决方案
与这个问题的其他部分一样,这将是defaultdict
时间......但我们需要OrderedDict
在这里保持原始时间戳顺序。
import collections
input_data = [
{
"timestamp": "21:15-21:30",
"logs": [{"exception": "IllegalAgrumentsException", "count": 1}],
},
{
"timestamp": "21:15-21:30",
"logs": [{"exception": "NullPointerException", "count": 2}],
},
]
logs_by_timestamp = collections.OrderedDict()
for datum in input_data:
logs_by_timestamp.setdefault(datum["timestamp"], []).extend(datum["logs"])
output_data = [
{"timestamp": timestamp, "logs": logs}
for (timestamp, logs) in logs_by_timestamp.items()
]
print(output_data)
输出(格式化)
[
{
"timestamp": "21:15-21:30",
"logs": [
{"exception": "IllegalAgrumentsException", "count": 1},
{"exception": "NullPointerException", "count": 2},
],
}
]
推荐阅读
- angular - Asp.Net Core 2.1 和 Angular 跨子域共享会话
- symfony - Symfony 4 验证实体/DTO 存在
- python-3.x - 即使在使用“rawvideo”作为编解码器参数后,Moviepy write_videofile 也会更改视频和音频帧的数量
- kdb - 从进程中识别和删除坏句柄的最佳方法是什么?
- php - 使用 Codeigniter 进行远程服务器同步
- c# - 在 Win10 的通知区域中自动删除或隐藏应用程序的通知
- excel - 汇总来自不同工作表的项目 Excel
- gradle - Kotlin 脚本:“包含”- 不能使用提供的参数调用以下函数
- excel - Excel 在另一个公式中使用数据透视表计数
- javascript - JavaScript 表单 onchange 获取 Nan