Nicolas Prange
Nicolas Prange

Reputation: 13

Python KeyError JSON

I am trying to get some specific data from a JSON file, but I get the following error:

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

This is my script, as you can see, I am trying to get Key regimes, because it has specific data, that others don't have:

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'])

And this is a small copy of 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
    }
]
}

How can I get the data inside of Key "regimes"?

Upvotes: 1

Views: 9907

Answers (2)

Mihir Bose
Mihir Bose

Reputation: 11

Try this piece of code:-

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

Make sure the indexes you are using are right.

Upvotes: 0

Hari Krishnan
Hari Krishnan

Reputation: 2079

In case if you have more than regimes in your json. I'm assuming so , since you gave only a part of your original json

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

This way the the program loops through each jsonobject and checks for the key regimes . If it exists, then it'll be printed

Upvotes: 2

Related Questions