简体   繁体   中英

python json Exception: KeyError 0

I am trying in a loop that I will create later to give out the names for an Api Post request (here for testing as print) but I always get the error Exception:KeyError 0.

Can someone help there?

file.json:

{ "_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

Problem:

I want to use an API with POST to create objects in a database. For this purpose I want to build a loop with Python that gives the json keys (00001,00002,...) one by one to the API. Like:

i = 0
while i < 10
data["_meta"]["Example1"][i]["name"]
API
i = i + 1

But my Problem is that 000001 is only an Example the real KeyName is a word such like

{ "_meta": {
        "Example1": {
            "Beta1231": {
                    "name": "Test-01",
                },
            "Frog00123": {
                    "name": "Test-02"
                },
            },
}

the exemple field is a dict not a list so instead of

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

you need to pass a keyname

data["_meta"]["Example1"]["key_name"]["name"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM