python - 如何从 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 对象,然后才能按预期访问键值对。
推荐阅读
- python-3.x - Python3 文件解析 - 重新打开文件?
- c - 如何在 macOS 上找到 C 头文件 errno.h 的位置?
- mysql - MySQL Docker 容器如果不存在则创建数据库
- xcode - 在 Info.plist 中将 Export Compliance 声明为 false 不会绕过 App Store Connect 上的提交过程
- ruby-on-rails - NoMethodError (undefined method `[]' for nil:NilClass): Ruby on Rails 即使使用 dig
- c - 这个带有两个递归调用的返回语句是如何工作的?
- c - 无法理解如何设置位
- javascript - 为什么只是通过?我想知道更多我需要解释
- node.js - NPM 安装失败了几个 ENOENT
- java - 在一个 Kafka Topic 下发送两个 Serialized Java 对象