Everyone. I'm new to python, and I've ran into an issue where I can get the value of a key that contains an underscore. I have the following JSON file that I load from disk. I can access the other values except for the one with an underscore in the key which is 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",
}
]
}
Here's what I have so far. It seems like the only way to access the key with the
underscore is if I test for it and I don't get why I can't just do device['cad_id']
and get the value. I'm not sure what I'm doing wrong, and if someone can tell me what's going on so I can understand it, I would very much appreciate it.
Thank you for your time.
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)
When I remove the comment where I print the cad_id, I get the following error
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'