我正在尝试从json api响应中提取一些配置信息。它会遍历父键,但不会检索嵌套在它们下面的值。
我尝试通过
对其进行迭代JSON响应如下:
{
"Id": null,
"result": {
"methodName": {
"config_1": {
"x": "asdf",
"y": "sdfg"
}
"config_2": {
"1": {
"a": "qwer",
"b": "wert",
"c": {
"x": "xxxx",
"y": "zzzz"
}
"2": {
"a": "qwer",
"b": "wert",
"c": {
"x": "xxxx",
"y": "zzzz"
}
}
}
}
}
我的代码如下:
def get_hardware_config(*args):
my_url = f"""<url>"""
try:
print(f"Retrieving configuration information for hardware")
api_method = f"<methodName>"
out = api_get(
my_url=my_url, name=api_method, my_user=<username>, my_pass=<password>
)
for item in out["result"]["methodName"]["config_2"]:
config_id = item
print(f"{config_id}")
serial = item["b"]
print(f"{identification}")
chassis_type = item["c"]["x"]
print(f"{chassis_type}")
model = item["c"]["y"]
print(f"{model}")
except (SystemExit, KeyboardInterrupt):
raise
except Exception as e:
logger.exception(f"Exception occured")
return []
get_hardware_config(hardware_name, ip)
如果我仅打印出项目,则效果很好
1
2
但是当我深入下面的项目时,它就会得到
Traceback (most recent call last):
File "./my_script.py", line 160, in get_hardware_config
serial = item["b"]
TypeError: string indices must be integers
请帮助
答案 0 :(得分:0)
在您的循环中,item
只是字典键,即"1"
或"2"
。
但是您真正想要的是该键的值。试试这个:
for config_id in out["result"]["methodName"]["config_2"]:
item = out["result"]["methodName"]["config_2"][config_id]
serial = item["b"]