【发布时间】:2020-03-30 06:32:56
【问题描述】:
我需要在 python3 的 requests 库中添加一些额外的键、值来响应而不更改响应结构(因为响应将被发送到进程的另一个服务)。例如,我收到了这样的回复:
>>import requests
>>r = requests.post(url=input_kong_address, data=data)
>>print(r.json())
{
"foo":"bar",
"key1":"val1"
}
我需要在回复中添加"extra_key":"extra_value":
{
"foo":"bar",
"key1":"val1",
"extra_key":"extra_value"
}
现在我想添加一些额外的响应键并将其发送到下一个服务而不改变结构(类、类型等):
>>import requests
>>import json
>>r = requests.post(url=input_kong_address, data=data)
>>response_data = r.json()
>>response_data['extra_key']='extra_value' # trying to add extra key and value to response
>>r.json = json.loads(json.dumps(response_data)) # trying to attach new dict to response
>>r.json() # check is worked?
{TypeError}'dict' object is not callable
谢谢。
【问题讨论】:
-
请在发布问题之前做一些实验。
-
json.dumps和json.loads是两个相反的操作,按照您的方式将其应用到字典中,会使效果无效。所以 json.loads(json.dumps(response_data)) 只返回 response_data。 -
response_data的类型为dictionary。因此 r.json 是字典类型(尽管执行这样的分配非常不聪明)Python 字典没有实现__call__方法。因此,它不是callable,正如错误所暗示的那样。 -
最后,如果您想修改收到的响应,则修改并将
response_data传递给下一个服务。没有什么需要做的了。喜欢:r2 = requests.get('next_service_url', data=response_data)
标签: python json python-requests