[英]Parsing JSON - TypeError: string indices must be integers
我需要检索 GoDaddy 证书名称和到期日期。 我正在尝试这样的代码:
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)
并得到如下错误:
cert_name = (cert['commonName'])
TypeError: string indices must be integers
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案子。
确保您收到的是您假设的数据类型。 如果解码产生包含dict
对象的list
实例,则您拥有的代码是合适的。 您收到的错误消息似乎是一个dict
。
当您遍历dict
时,您将收到它的所有键。 如果您确切知道所需的密钥,则无需对其进行迭代。
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'])
如果密钥不存在,这将引发错误。 另一种尝试在没有任何异常的情况下检索它的方法是:
common_name = cert_dict.get('commonName')
如果密钥不存在, common_name
将为None
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.