0
header = {'Content-type': 'application/json','Authorization': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' }  
url = 'https://sandbox-authservice.priaid.ch/login'
response = requests.post(url, headers = header, verify=False).json()
token = json.dumps(response)
print token['ValidThrough']

我想在我的 webhook 中打印 ValidThrough 属性,该属性通过 POST 调用作为 JSON 数据接收。我知道这已经被问过很多次了,但是 print token['ValidThrough'] 对我不起作用。我收到错误“TypeError:字符串索引必须是整数,而不是 str”

4

2 回答 2

2

由于响应似乎已经在 json 中,因此无需使用json.dumps.

json.dumps在字典上将返回一个无法明显索引的字符串,因此会出现该错误。

于 2016-07-29T10:11:57.517 回答
0

请求响应.json()方法已经将字符串的内容加载到 json。

您应该使用它,但是您的代码稍后将其序列化回字符串,因此错误(token是您期望的 dict 的字符串表示形式,而不是 dict)。您应该省略该json.dumps(response)行,并使用response['ValidThrough']

这里还有另一个错误,即使您假设.json()返回的字符串应该再次反序列化,您应该使用json.loads(response)它来将其加载到字典中(而不是转储以再次序列化它)

于 2016-07-29T10:32:01.743 回答