如何使用python从嵌套的json获取数据?

时间:2018-11-01 19:59:46

标签: python json

我正在尝试从此api响应中获取一些数据。 尝试打印杀死的数量,但我不知道如何。 因为在“统计”之后有很多“元数据”键。

这是代码

import requests 
import json
import sys

url = 'https://cod-api.tracker.gg/v1/standard/bo4/profile/1/Edr1X'
headers = {'secret'}
 r = requests.get(url, headers=headers)

print(r.text)

#Get Kills amount
data = r.text


#load the json to a string
 resp = json.loads(data)

#get the stats
print (resp['data']['stats'])

#get the amount of kills how?
print (resp['data']['stats']['metadata']['kills'])

这是print r.text的响应

{
    "data": {
        "id": "9d0cd2c0-9408-4925-908d-5fcf0dfeb0b9",
        "type": "player",
        "metadata": {
            "statsCategoryOrder": [
                "levels",
                "combat",
                "game",
                "bullets",
                "ekia-enemy-killed-in-action",
                "objective",
                "team-play",
                "extra"
            ],
            "platformId": 1,
            "platformUserHandle": "Edr1X",
            "accountId": "9d0cd2c0-9408-4925-908d-5fcf0dfeb0b9",
            "cacheExpireDate": "11/1/2018 7:21:38 PM"
        },
        "stats": [
            {
                "metadata": {
                    "key": "level",
                    "name": "Level",
                    "categoryKey": "levels",
                    "categoryName": "Levels",
                    "isReversed": false,
                    "iconUrl": "https://cod-cdn.tracker.gg/assets/ranks/rank_13.png"
                },
                "value": 13,
                "percentile": 83,
                "displayValue": "13"
            },
            {
                "metadata": {
                    "key": "KDRatio",
                    "name": "KD Ratio",
                    "categoryKey": "combat",
                    "categoryName": "Combat",
                    "isReversed": false
                },
                "value": 0.78,
                "percentile": 85,
                "displayValue": "0.78",
                "displayRank": ""
            },
            {
                "metadata": {
                    "key": "Kills",
                    "name": "Kills",
                    "categoryKey": "combat",
                    "categoryName": "Combat",
                    "isReversed": false
                },
                "value": 161,
                "percentile": 86,
                "displayValue": "161",
                "displayRank": ""
            },
            {
                "metadata": {
                    "key": "Deaths",
                    "name": "Deaths",
                    "categoryKey": "combat",
                    "categoryName": "Combat",
                    "isReversed": false
                },
                "value": 206,
                "percentile": 83,
                "displayValue": "206",
                "displayRank": ""
            },
            {
                "metadata": {
                    "key": "Assists",
                    "name": "Assists",
                    "categoryKey": "combat",
                    "categoryName": "Combat",
                    "isReversed": false
                },
                "value": 61,
                "percentile": 81,
                "displayValue": "61",
                "displayRank": ""
            },
            {
                "metadata": {
                    "key": "Melee",
                    "name": "Melee",
                    "categoryKey": "combat",
                    "categoryName": "Combat",
                    "isReversed": false
                },
                "value": 4,
                "percentile": 32,
                "displayValue": "4",
                "displayRank": ""
            },
            {
                "metadata": {
                    "key": "Suicides",
                    "name": "Suicides",
                    "categoryKey": "combat",
                    "categoryName": "Combat",
                    "isReversed": false
                },
                "value": 0,
                "displayValue": "0",
                "displayRank": ""
            },       

        ]
    }
}

我如何获得杀戮的价值? 我是否必须遍历“元数据”?有for循环?

1 个答案:

答案 0 :(得分:1)

print([metadata['value'] for metadata in resp['data']['stats'] if metadata['metadata']['key'] == 'Kills'])

使用列表推导来遍历每个元数据,以查看其键是否为'Kills'

或者,如果kills始终是列表的相同索引,则只需请求该列表位置即可。

这是我为验证您的信息而写的测试:

def test_get_kills(self):
    import json
    resp = json.loads(resp)
    kills = [metadata['value'] for metadata in resp['data']['stats'] if metadata['metadata']['key'] == 'Kills']
    self.assertEqual(161, next(kills))

如果列表理解不是您的事(应该是),那么循环中的等效项将是:

for metadata in resp['data']['stats']:
    if metadata['metadata']['key'] == 'Kills':
        kills = metadata['value']