Home > Back-end >  Python Json dict Variable
Python Json dict Variable

Time:08-11

I am trying in a loop that I will create later to give out the names(single) for an Api Post request (here for testing as print) and Change the Vaule oft the Variable in each turn of the loop. Now im running in Exception:KeyError 0.

My question is. Is there an Variable that i can use for [0] (Key_name)

Can someone help there?

file.json:

(Shortened, the real file is much longer)

{ "_meta": {
        "Example1": {
            "00000001": {
                    "name": "Test-01",
                },
            "00000002": {
                    "name": "Test-02"
                },
            },
}
import json

data = json.load(open("file.json"))

name = data["_meta"]["Example1"][0]["name"]


print(f"Name: {name}")

Exception: KeyError 0

Edit

        "Example1": {
            "00000001": {
                    "name": "Test-01",

                },
            "00000002": {
                    "name": "Test-02"
                    "uuid": "Test-uuid"
                    "config": {
                          "ipAdresse": "Test-Ip"
                     },
                },
            },
}

CodePudding user response:

the issue is the [0], the value for the Example1 element is not a list but a dict. Try using dict.items()

for key, value in data["_meta"]["Example1"].items():
    print(f"Key: {key}\nName: {value['name']}")

EDIT for the comment below:

So you need to test if a key exists inside the dict items to avoid the key not found errors. You can do so by simply checking if keyname in dict

See the extended example below...

data = {
    "_meta":{
        "Example1":{
            "00000001":{
                "name":"Test-01"
            },
            "00000002":{
                "name":"Test-02",
                "uuid":"Test-uuid",
                "config":{
                    "ipAdresse":"Test-Ip"
                }
            }
        }
    }
}

for key, value in data["_meta"]["Example1"].items():
    print(f"Key: {key}\n  Name: {value['name']}")
    # check if the key exists. fe 00000001 does not have the uuid nor config key
    if "uuid" in value:
        print(f"  uuid: {value['uuid']}")
    if "config" in value and "ipAdresse" in value["config"]:
        print(f"  ipAdresse: {value['config']['ipAdresse']}")

output

Key: 00000001
  Name: Test-01
Key: 00000002
  Name: Test-02
  uuid: Test-uuid
  ipAdresse: Test-Ip
  • Related