简体   繁体   中英

Parsing JSON - TypeError: string indices must be integers

I need to retrieve GoDaddy certificates name and expiration dates. I`m trying code like this:

def get_cert():
    customerId = "UUID"
    cert_url = "https://api.godaddy.com//v2/customers/%s/certificates" %(customerId)

    cert_response = requests.get(cert_url, headers=headers)
    cert_dict = json.loads(cert_response.text)
    for cert in cert_dict:
        cert_name = (cert['commonName'])
        print(cert_name)

and getting error like:

    cert_name = (cert['commonName'])
TypeError: string indices must be integers

Output from the API call without parsing:

        {
            "certificateId": "ID", 
            "commonName": "*.domain.co.uk", 
            "completedAt": "2021-01-12T14:26:36Z", 
            "createdAt": "2020-04-02T14:25:06Z", 
            "period": 1, 
            "serialNumber": "NUMBER", 
            "status": "CURRENT", 
            "type": "DV_WILDCARD_SSL", 
            "validEndAt": "2022-05-04T14:26:32Z", 
            "validStartAt": "2021-04-02T14:26:32Z"
        }

I have the same code for GoDaddy domains API and it works properly (logic is the same, difference only in API URL and keys) so I can`t understand why its forbidden to cut json output by "commonName" and "validEndAt" in this case.

Be sure that what you are receiving is the data type you are assuming it is. The code you have is suitable if the decoding yields a list instance containing dict objects. The error message you are receiving seems like you are getting a single dict .

When you iterate through a dict , you will receive all its keys. If you know exactly what key you want, you don't need to iterate over it.

def get_cert():
    customerId = "UUID"
    cert_url = "https://api.godaddy.com//v2/customers/%s/certificates" %(customerId)

    cert_response = requests.get(cert_url, headers=headers)
    cert_dict = json.loads(cert_response.text)
    print(cert_dict['commonName'])

This will throw an error if the key does not exist. Another way to try to retrieve it without any exceptions would be:

common_name = cert_dict.get('commonName')

If the key is not there, common_name would be None

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