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"
                },
            },
}
6
  • data["_meta"]["Example1"] is a dictionary, not a list. It doesn't have a 0 key but "00000001" and "00000002", so KeyError is expected. Commented Aug 10, 2022 at 9:33
  • @alec_djinn Do you have any idea how the [0] can be a variable and not a fixed value? Commented Aug 10, 2022 at 10:48
  • I don't quite get what you are asking. Something like this k="00000001" and then name = data["_meta"]["Example1"][k]["name"] ? What is your goal? Please try describing your problem in a more exhaustive way. Check stackoverflow.com/help/how-to-ask and stackoverflow.com/help/minimal-reproducible-example Commented Aug 10, 2022 at 12:16
  • @alec_djinn In the Topic beacuse the Code was not shown right in a comment Commented Aug 10, 2022 at 12:44
  • It is not clear if you know the keys or not. In your example, it looks like you know them because you can get them from data["_meta"]["Example1"].keys(). So, again, I don't quite get what is the problem here. Commented Aug 10, 2022 at 13:51

1 Answer 1

1

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"]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer but I needed a variable key name there.

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.