在python中将列表转换为特定的json
我正在处理一个问题,我的输出是这样的:在python中将列表转换为特定的json,python,arrays,json,python-3.x,list,Python,Arrays,Json,Python 3.x,List,我正在处理一个问题,我的输出是这样的:列表,其中包含长字符串 ["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: [ {
列表,其中包含长字符串
["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
打印(类型(输入))//
input=re.split(r',\s+',input[0])
打印(输入)/['21:15-21:30 IllegalAgrumentsException 1,
21:15-21:30 NullPointerException 2….']
输出=collections.defaultdict(collections.Counter)
对于行输入:
时间,错误,计数=行。拆分(无,2)
输出[time][error]+=int(count)//基数为10的int()的文本无效:“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)
输出(格式化)
Python有一个json库,可以将列表转换为json,但要归档您发布的这种特定格式,您必须事先解析列表,例如使用正则表达式。注释不用于扩展讨论;这段对话已经结束。
[
{
"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,
}
],
},
]