首页 > 解决方案 > JSON有效负载的Python字符串连接

问题描述

我正在尝试修改 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'))

标签: pythonjsonstring-concatenation

解决方案


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

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

您可以只对数据使用字典。


推荐阅读