如何从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)

尝试以下操作:

通过声明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对象,然后才能按预期访问键值对。

响应可以用以下方法解析:

response.json()['somekey']

或更常见的

response.json().get('somekey')

从@DavidCulbreth

Response({res.json()['somekey']}, status=200)试图将响应放入set()中,这就是为什么它抛出TypeError: unhashable type: 'dict'

最新更新