【问题标题】:Access JSON data in Python在 Python 中访问 JSON 数据
【发布时间】:2016-07-29 10:07:02
【问题描述】:
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: string indices must be integers, not str”

【问题讨论】:

  • 是的,它也是返回值,它有两个属性,'Token' 和 'ValidThrough'

标签: python json hook.io


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-29
      • 2022-11-02
      • 2019-03-02
      • 1970-01-01
      • 1970-01-01
      • 2019-04-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多