2 回答
TA贡献1772条经验 获得超5个赞
尝试一下:
json_data = ... # load your json file
for item in json_data:
new_data = []
for data in item["Data"]:
data_item = dict()
data_item["Domain_name"] = data["name"][0]
data_item["Domain_Id"] = data["name"][1]
data_item["app"] = data["name"][2]
data_item["appId"] = data["name"][3]
data_item["sum"] = data["results"][0]["sum"]
new_data.append(data_item)
item["Data"] = new_data
输出:
[
{'Data': [
{'Domain_name': ' Devlopment',
'Domain_Id': '34876',
'app': 'Tez',
'appId': '4578',
'sum': 54},
{'Domain_name': 'production',
'Domain_Id': '09876',
'app': 'phonepay',
'appId': '2312',
'sum': 50.0}],
'totalResult': {'results': [{'sum': 2027.0}]},
'unknownGroup': {'results': [{'sum': 0.0}]},
'performanceStats':
{'fileReadCount': 1,
'decompressionCount': 0,
'decompressionCacheEnabledCount': 0},
'metadata':
{'eventTypes': ['Data_collection'],
'eventType': 'Data_collection',
'openEnded': True}},
{'Data': [
{'Domain_name': ' Quality_Analyst',
'Domain_Id': '623456',
'app': 'slicepay',
'appId': '989766',
'sum': 54},
...
TA贡献1804条经验 获得超3个赞
试试这个代码:这里是 json_dic 你的 JSON-Data
def change_format(val_lst):
key_lst = ['Domain_name','Domain_Id','app','appId']
res_lst = []
for dic in val_lst:
temp_dic = {key_lst[i]:val for i,val in enumerate(dic['name'])}
temp_dic['sum'] = dic['results'][0]['sum']
res_lst.append(temp_dic)
return res_lst
print(list(map(lambda x:dict([(key,change_format(val_lst)) if key=='Data' else (key,val_lst) for key,val_lst in x.items()]),json_dic)))
结果:
[{'Data': [{'Domain_name': ' Devlopment', 'Domain_Id': '34876', 'app': 'Tez', 'appId': '4578', 'sum': 54}, {'Domain_name': 'production', 'Domain_Id': '09876', 'app': 'phonepay', 'appId': '2312', 'sum': 50.0}], 'totalResult': {'results': [{'sum': 2027.0}]}, 'unknownGroup': {'results': [{'sum': 0.0}]}, 'performanceStats': {'fileReadCount': 1, 'decompressionCount': 0, 'decompressionCacheEnabledCount': 0}, 'metadata': {'eventTypes': ['Data_collection'], 'eventType': 'Data_collection', 'openEnded': 'true'}}, {'Data': [{'Domain_name': ' Quality_Analyst', 'Domain_Id': '623456', 'app': 'slicepay', 'appId': '989766', 'sum': 54}, {'Domain_name': 'Testing', 'Domain_Id': '7654', 'app': 'krazybee', 'appId': '1234', 'sum': 50.0}], 'totalResult': {'results': [{'sum': 2027.0}]}, 'unknownGroup': {'results': [{'sum': 0.0}]}, 'performanceStats': {'fileReadCount': 1, 'decompressionCount': 0, 'decompressionCacheEnabledCount': 0}, 'metadata': {'eventTypes': ['Data_collection'], 'eventType': 'Data_collection', 'openEnded': 'true'}}]
使用我的函数来更改 new_json 数据的格式,我只是使用列表理解来更改 new_data.Happy Coding
添加回答
举报