简体   繁体   English

python json 异常:KeyError 0

[英]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.我正在尝试在稍后创建的循环中给出 Api 发布请求的名称(此处用于测试打印),但我总是收到错误异常:KeyError 0。

Can someone help there?有人可以帮忙吗?

file.json:文件.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例外:KeyError 0

Problem:问题:

I want to use an API with POST to create objects in a database.我想使用带有 POST 的 API 在数据库中创建对象。 For this purpose I want to build a loop with Python that gives the json keys (00001,00002,...) one by one to the API.为此,我想用 Python 构建一个循环,将 json 密钥(00001,00002,...)一一提供给 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但我的问题是 000001 只是一个例子,真正的 KeyName 是一个像这样的词

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

the exemple field is a dict not a list so instead of exemple字段是dict而不是list ,所以不是

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

you need to pass a keyname你需要传递一个键名

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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