尝试使用API访问有关服务器存储的详细信息时出现错误。我想提取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
如何访问状态* ? 整个想法是最后使用以下代码获取有关状态的信息:
if bkpsts == "online":
print('Backup has been created.')
else bkpsts == "backuping":
print('Backup creation is in progress.')
else:
print(bkpdet.status_code)
我正在搜索,但仍然找不到这里的问题。
答案 0 :(得分:2)
使用时:
for sts in datastg['storage']:
sts
将是一个字符串键。您正在尝试像字典一样对待它。
如果您只需要state
值,则可以直接访问它:
datastg['storage']['state']
如果要迭代storage
下的所有键值对,则可以使用items()
来键和值。
for key, value in datastg['storage'].items():
print(key,":", value)
答案 1 :(得分:1)
正如@MarkMeyer所建议的那样,我更改了这样的代码:
bkpdet = requests.get('https://fffff.com/1.2/storage/08475', auth=HTTPBasicAuth('login', 'pass'))
bkpdet_json = bkpdet.json()
datastg = bkpdet.json()
bkpsts = datastg['storage']['state']
print(bkpsts)
它运作完美!
答案 2 :(得分:0)
下面的代码有效
data = {
"storage": {
"access": "private",
"backup_rule": {},
"backups": {
"backup": []
},
"license": 0,
"part_of_plan": "",
"servers": {
"server": [
""
]
},
"size": 1,
"state": "online",
"tier": "",
"title": "",
"type": "",
"uuid": "",
"zone": ""
}
}
state = data['storage']['state']
print(state)
输出
online