1

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"?

1
  • 1
    data['perfil'][4]['regimes'] Commented Aug 13, 2018 at 12:25

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

The call to keys is superfluous; a dict iterator yields the keys of the dict.
Thank you, it fixed my problem o/////
0

Try this piece of code:-

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

Make sure the indexes you are using are right.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.