python - 在python中将列表转换为特定的json
问题描述
我正在解决一个问题,我的输出是这样的:List with long string inside it
["21:15-21:30 IllegalAgrumentsException 1,
21:15-21:30 NullPointerException 2,
22:00-22:15 UserNotFoundException 1,
22:15-22:30 NullPointerException 1
....."]
我需要像这样转换数据:
response: [
{
"time": "21:15-21:30",
"logs": [
{
"exception": "IllegalAgrumentsException",
"count": 1
},{
"exception": "NullPointerException",
"count": 2
}
]
},
{
"time": "22:00-22:15",
"logs": [
{.....
}
]
}
]
如何将数据转换为这种特定格式?
错误 :
print(type(input)) // <class 'list'>
input = re.split(r',\s+', input[0])
print(input) // ['21:15-21:30 IllegalAgrumentsException 1,
21:15-21:30 NullPointerException 2.....']
output = collections.defaultdict(collections.Counter)
for line in input:
time, error, count = line.split(None, 2)
output[time][error] += int(count) //invalid literal for int() with base 10: '1
解决方案
我假设您的输入列表实际上是一个字符串列表,但如果不是,您可以先拆分字符串:
import re
# If the input data is a list that has one entry, peel it off
input_data = input_data[0]
# Now we should have a string to split...
input_data = re.split(r',\s*', input_data)
像往常一样,分组和整理操作collections.defaultdict
(在这种特殊的求和情况下collections.Counter
也是如此)派上用场:
import collections
input_data = [
"21:15-21:30 IllegalAgrumentsException 1",
"21:15-21:30 NullPointerException 2",
"22:00-22:15 UserNotFoundException 1",
"22:15-22:30 NullPointerException 1",
]
output = collections.defaultdict(collections.Counter)
for line in input_data:
time, error, count = line.split(None, 2)
output[time][error] += int(count)
response = [
{
"time": time,
"logs": [
{"exception": exception, "count": count}
for (exception, count) in counter.items()
],
}
for (time, counter) in output.items()
]
print(response)
输出(格式化)
[
{
"time": "21:15-21:30",
"logs": [
{
"exception": "IllegalAgrumentsException",
"count": 1,
},
{
"exception": "NullPointerException",
"count": 2,
},
],
},
{
"time": "22:00-22:15",
"logs": [
{
"exception": "UserNotFoundException",
"count": 1,
}
],
},
{
"time": "22:15-22:30",
"logs": [
{
"exception": "NullPointerException",
"count": 1,
}
],
},
]
推荐阅读
- nginx - 使用 docker-compose 将 nginx.conf 负载平衡更正为 uvicorn FastAPI
- ionic-framework - Ionic build android 找不到 Android AVD
- powershell - 使用自定义对象对 PowerShell OrderedDictionary 进行排序
- c# - 将访问数据插入 .CSV 并随时间插入数据
- swift - SwiftUI - 按钮 - 如何将函数(带参数)请求从子级传递给父级
- javascript - React 不响应调度的更改事件
- zap - 如何通过重定向到已验证部分来验证 SPA
- typescript - 是否可以在 Typescript 中创建可组合的实用程序类型?
- python - 如何使用 pandas 为数据框创建函数
- java - 获得 2 字节 [] 数组之间数值差异的更快方法?