访问 Python 中的 JSON 数据

Access JSON data in Python

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'] isnt working for me.I 收到错误 "TypeError: string indices must be integers, not str"

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

字典上的

json.dumps 将 return 一个无法明显索引的字符串,因此会出现错误。

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

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

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