Reputation: 3
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"
},
},
}
Upvotes: 0
Views: 616
Reputation: 1067
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"]
Upvotes: 1