JSONを実際にトレーニングして、2つの異なるキーを使用して新しいJSONをどのように解析できるかを理解しようとしています。私は、データ検証の目的でいくつかのログを並べ替える必要があります。Pythonで複数のキーを使用して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を取得することはできません、あなたは何か考えていますか?
おかげで、それは魔法のように動作します。私の場合、JSONファイルを使用するときには、json.loadで呼び出す必要があります.json.loadsではなく、コードを試してみる必要があります。 – SandaleRaclette