简体   繁体   English

解析 JSON - TypeError:字符串索引必须是整数

[英]Parsing JSON - TypeError: string indices must be integers

I need to retrieve GoDaddy certificates name and expiration dates.我需要检索 GoDaddy 证书名称和到期日期。 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: Output 来自 API 调用,无需解析:

        {
            "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. 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案子。

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.如果解码产生包含dict对象的list实例,则您拥有的代码是合适的。 The error message you are receiving seems like you are getting a single dict .您收到的错误消息似乎是一个dict

When you iterate through a dict , you will receive all its keys.当您遍历dict时,您将收到它的所有键。 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如果密钥不存在, common_name将为None

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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