尝试使用Python通过API访问数据时出错 [英] Error when trying to access data via API using Python
问题描述
尝试使用API访问有关服务器存储的详细信息时出现错误.我想提取json中的状态的备份状态:
I get error when trying to access details about servers storage using API. I want to extract backup status which is state in json:
{
"storage": {
"access": "private",
"backup_rule": {},
"backups": {
"backup": []
},
"license": 0,
"part_of_plan": "",
"servers": {
"server": [
""
]
},
"size": ,
"state": "online",
"tier": "",
"title": "",
"type": "",
"uuid": "",
"zone": ""
}
}
当我执行此代码时:
bkpdet = requests.get('https://fffff.com/1.2/storage/08475', auth=HTTPBasicAuth('login', 'pass'))
bkpdet_json = bkpdet.json()
datastg = bkpdet.json()
print(datastg)
for sts in datastg['storage']:
bkpsts = sts['state']
print(bkpsts)
我收到此错误:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
TypeError: string indices must be integers
如何访问状态* ? 整个想法是最后使用以下代码获取有关状态的信息:
How can I access state*? The whole idea is to at the end get info about status using this code:
if bkpsts == "online":
print('Backup has been created.')
else bkpsts == "backuping":
print('Backup creation is in progress.')
else:
print(bkpdet.status_code)
我正在搜索,但仍然找不到这里的问题.
I was searching but still cannot find what is wrong here.
推荐答案
使用时:
for sts in datastg['storage']:
sts
将是一个字符串键.您正在尝试像字典一样对待它.
sts
will be a string key. You are trying to treat it like an dictionary.
如果只需要state
值,则可以直接访问它:
If you just need the state
value, you can access it directly:
datastg['storage']['state']
如果要迭代storage
下的所有键值对,则可以同时使用items()
键和值.
If you want to iterate all key value pairs under storage
, you can use items()
to both key and value.
for key, value in datastg['storage'].items():
print(key,":", value)
这篇关于尝试使用Python通过API访问数据时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!