简体   繁体   English

Python Json 字典变量

[英]Python Json dict Variable

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.我正在尝试一个循环,稍后我将创建一个循环,以给出 Api 发布请求的名称(单个)(此处用于测试为打印)并在循环的每一轮中更改变量的值。 Now im running in Exception:KeyError 0.现在我在异常中运行:KeyError 0。

My question is.我的问题是。 Is there an Variable that i can use for [0] (Key_name)是否有一个变量可以用于[0] (Key_name)

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

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

the issue is the [0] , the value for the Example1 element is not a list but a dict.问题是[0]Example1元素的值不是列表而是字典。 Try using dict.items()尝试使用dict.items()

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

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

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