简体   繁体   中英

Error when trying to access data via API using Python

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": ""
   }
}

When I execute this code:

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)

I get this error:

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.

When you use:

for sts in datastg['storage']:

sts will be a string key. You are trying to treat it like an dictionary.

If you just need the state value, you can access it directly:

datastg['storage']['state']

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)

As @MarkMeyer advised I changed code like this:

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)

It works perfectly!

The code below works

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)

output

online

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM