为了账号安全,请及时绑定邮箱和手机立即绑定

JSON 负载的 Python 字符串连接

JSON 负载的 Python 字符串连接

RISEBY 2023-12-29 10:31:38
我正在尝试修改 Postman 生成的这段代码,以用字符串变量替换硬编码字符串,但我不断收到KeyError: '\n\t"username"'这是代码username = "jose"email = "some_email"password = "1234"url = "some_url"payload = '{\n\t\"username\": {},\n\t\"email\": {},\n\t\"password\": {}\n}'.format(username, email, password)headers = {  'Content-Type': 'application/json'}response = requests.request("POST", url, headers=headers, data=payload)print(response.text.encode('utf8'))
查看完整描述

2 回答

?
Helenr

TA贡献1780条经验 获得超3个赞

你可以这样正确地形成你的json:


import json

username = "jose"

email = "some_email"

password = "1234"


url = "some_url"


payload = json.dumps({"username": username, "email":email, "password":password}, indent=4)

headers = { 'Content-Type': 'application/json'}


response = requests.request("POST", url, headers=headers, data=payload)


print(response.text.encode('utf8'))


查看完整回答
反对 回复 2023-12-29
?
长风秋雁

TA贡献1757条经验 获得超7个赞

看看这里的例子:https ://requests.readthedocs.io/en/master/user/quickstart/

>>> r = requests.post('https://httpbin.org/post', data = {'key':'value'})

您可以只使用字典来获取数据。


查看完整回答
反对 回复 2023-12-29
  • 2 回答
  • 0 关注
  • 58 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信