Python KeyError JSON

时间:2018-08-13 12:20:53

标签: python json

我正在尝试从JSON文件中获取某些特定数据,但出现以下错误:

for item in data['perfil'][0]['regimes']: KeyError: 'regimes'

这是我的脚本,如您所见,我正在尝试获取密钥regimes,因为它具有特定的数据,而其他人却没有:

import json
import matplotlib.pyplot as plt

with open('backupperfil.json') as f:
    data = json.load(f)

for item in data['perfil'][0]['regimes']:
    print(item['classificacao'])

这是Json File的一个小副本:

{
"perfil":[
    {
        "data": 1533815887,
        "kmh": 0,
        "rpm": 0.0,
        "pedal": 15.294117647058824
    },
    {
        "data": 1533815888,
        "kmh": 0
        ,"rpm": 0.0
        ,"pedal": 15.294117647058824
    },
    {
        "data": 1533815889,
        "kmh": 0
        ,"rpm": 0.0
        ,"pedal": 15.294117647058824
    },
    {
        "kmh": 0
        ,"rpm": 834.75
        ,"pedal": 14.117647058823529
    },
    {
        "regimes": [
            {
                "kmh": 0,
                "rpm": 833.75,
                "pedal": 14.117647058823529,
                "regime_inferior_normal": 318,
                "regime_normal": 27,
                "regime_agressivo": 1,
                "regime_muito_agressivo": 0,
                "soma_regimes": 346,
                "classificacao": "Regime Inferior a Normal"
            }
        ]
    },
    {
        "kmh": 0,
        "rpm": 827.5,
        "pedal": 14.117647058823529
    }
]
}

如何获取关键“制度”中的数据?

2 个答案:

答案 0 :(得分:1)

以防万一,如果您的json中包含多个制式。我假设是这样,因为您只给出了原始json的一部分

for i in js['perfil']:
    if 'regimes' in i:
        print(i['regimes'][0]['classificacao'])

通过这种方式,程序循环遍历每个json对象,并检查键regimes。如果存在,它将被打印

答案 1 :(得分:0)

尝试这段代码:-

data['perfil'][4]['regimes'][0]['classificacao']

确保所使用的索引正确。