每个人。我是 python 的新手,我遇到了一个问题,我可以获取包含下划线的键的值。我有从磁盘加载的以下 JSON 文件。除了键中有下划线的值之外,我可以访问其他值cad_id
{
"meta": {
"summary": "devices are stored here"
},
"devices": [
{
"type": "printer device",
"id": "1",
"name": "storage_printer",
"cad_id": "printer"
},
{
"type": "email device",
"id": "1497041417932",
"name": "email",
"cad_id": "tfd04",
},
{
"type": "zone device",
"id": "1497041431054",
"name": "Page",
"cad_id": "page1",
}
]
}
这是我到目前为止所拥有的。似乎使用下划线访问密钥的唯一方法是如果我测试它并且我不明白为什么我不能只是做device['cad_id']并获得价值。我不确定我做错了什么,如果有人能告诉我发生了什么以便我理解它,我将不胜感激。
感谢您的时间。
import socket
import json
def load_config():
filepath = "/var/www/html/fac3-config.json"
with open(filepath) as file_object:
config = json.load(file_object)
return config
def get_device_by_cad_id(cad_id, config):
devices = config["devices"]
for device in config["devices"]:
#print(device['cad_id']) -- this doesn't work
print(device['id']) #this works
# this is the only way that I can access the value of cad_id
# and I don't understand why
#if "cad_id" in device:
# if device['cad_id'] == cad_id:
# return device['id']
config = load_config()
device_id = get_device_by_id("page1", config)
print(device_id)
当我删除打印 cad_id 的注释时,出现以下错误
Traceback (most recent call last):
File "trigger_hub.py", line 23, in <module>
device_id = get_device_by_cad_id("page1", config)
File "trigger_hub.py", line 13, in get_device_by_cad_id
print(device['cad_id'])
KeyError: 'cad_id'
不负相思意
相关分类