首页 > 解决方案 > 如何从 django 响应中解析属性

问题描述

我有一个来自请求的响应对象,格式如下:

url = 'http://localhost:8000/some-endpoint'
body = {
    'key': 'val'
}
response = requests.post(url, json=body)

并希望以以下形式从响应中访问密钥:

[
  [
    "{\"somekey\": \"abcabcabc\", \"expires_in\": 86400}"
  ]
]

我尝试使用各种方法进行访问someKey,但出现错误

response.json()
# TypeError: unhashable type: 'dict'


json.dumps(response).json()
# TypeError: Object of type Response is not JSON serializable


response[0]['somekey']
# TypeError: 'Response' object is not subscriptable


response.get('somekey')
# AttributeError: 'Response' object has no attribute 'get'


response.text
["{\"access_token\": \"j9U9QHChSrEVitXeZSv400AQfq3imq\", \"expires_in\": 86400, \"token_type\": \"Bearer\", \"scope\": \"read write\"}"]

response.text.json()
# 'str' object has no attribute 'json'

如何访问 的值somekey

注意:response对象正在被包装以便在 Postman 中进行调试,例如:

return Response({
    res.json().get('access_token')
}, status=200)

标签: pythonjsonresponse

解决方案


尝试以下操作:

通过声明 JSON_HEADERS 常量并将其作为关键字参数传递,确保您的响应返回有效的 JSON:

JSON_HEADERS = {
    'Content-Type': "application/json",
    'Accept': "application/json"
}

然后正确序列化您的body变量并打印您需要的密钥:

body = json.dumps({
  'key': 'val'
})
response = requests.post(url, headers=JSON_HEADERS, json=body)

您的端点在第一个索引处返回一个带有字符串的列表。尝试这个:

r = json.loads(response[0])
r['key']
<value of key>

您需要将字符串转换为 dict 对象,然后才能按预期访问键值对。


推荐阅读