更改列表后,我得到了回应。我的回复看起来像这样:
{
"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中那样将日志合并在一起?
答案 0 :(得分:2)
与other part of this question一样,这将是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},
],
}
]
答案 1 :(得分:1)
考虑您的情况。
查看以下补丁
_dict = {
"response": [
{
"timestamp": "21:15-21:30",
"logs": [
{
"exception": "IllegalAgrumentsException",
"count": 1
}
]
},
{
"timestamp": "21:15-21:30",
"logs": [
{
"exception": "NullPointerException",
"count": 2
}
]
}]}
_final = {}
for _dict in _dict.get('response'):
if not _dict.get('timestamp') in _final:
_final[_dict.get('timestamp')] = {
'timestamp': _dict.get('timestamp'),
'logs': []
}
_final[_dict.get('timestamp')]['logs'] += _dict.get('logs')
_result ={'response': list(_final.values())}
print(_result)
将打印...
{
'response': [
{
'timestamp': '21:15-21:30',
'logs': [
{
'exception': 'IllegalAgrumentsException',
'count': 1
},
{
'exception': 'NullPointerException',
'count': 2
}
]
}
]
}
答案 2 :(得分:0)
response = [
{
"timestamp": "21:15-21:30",
"logs": [{"exception": "IllegalAgrumentsException", "count": 1}],
},
{
"timestamp": "21:15-21:30",
"logs": [{"exception": "NullPointerException", "count": 2}],
},
]
final = []
for k,v in groupby(response, lambda x:x.pop('timestamp')):
final.append({
'timestamp':k,
'logs':reduce(
lambda x,y: {'logs':y['logs']+x['logs']},
[*v]
)['logs']
})
print(final)
Output
[
{
"timestamp": "21:15-21:30",
"logs": [
{"exception": "IllegalAgrumentsException", "count": 1},
{"exception": "NullPointerException", "count": 2},
],
}
]