【发布时间】:2017-11-20 17:42:57
【问题描述】:
实际使用 JSON 进行培训,试图了解如何使用两个不同的键解析新的 JSON。我想对一些日志进行排序以用于数据可视化。
我的数据 JSON
{
"productTitle": "Product",
"apiName": "soapwebservice"
"statusCode": "200 OK"
},
{
"productTitle": "Product",
"apiName": "productionservice",
"statusCode": "200 OK"
},
{
"productTitle": "Product",
"apiName": "firstapi",
"statusCode": "200 OK"
},
{
"productTitle": "Product",
"apiName": "firstapi",
"statusCode": "200 OK"
},
{
"productTitle": "Suitability",
"apiName": "suitability-api",
"statusCode": "200 OK"
}
预期的输出 JSON:
{
"Product": 4,
"api-activity": {
"soapwebservice": 1,
"productionservice": 1,
"firstapi": 2
}
}
{
"Suitability": 1,
"api-activity": {
"suitability-api": 1,
}
}
这是我第一个解析和计算第一个键的代码:
import json
from collections import Counter
with open('events1.json') as json_data:
json_obj = json.load(json_data) # Read the JSON file
# print(json_obj['calls'][0]['appName']); #Example JSON Extract
c = Counter(player['productTitle'] for player in json_obj['calls'])
with open('output.json', 'w') as f:
f.write(json.dumps(c, indent=4)) # Parse and write the file
print("Translation of JSON");
我正在寻找一种获取预期 JSON 的方法,可能带有一个循环,如下所述:parse JSON values by multilevel keys 但是我无法按预期获取 JSON,您知道吗?
【问题讨论】: