Skip to main content
 首页 » 编程设计

python之将 curl PUT 转换为 Python 请求的问题 : "Problems parsing JSON"

2025年05月04日16JeffreyZhao

我希望使用 Python requests图书馆 create a new file in a GitHub存储库。在命令行中输入以下内容对我有用(根据需要替换 LOGIN 和 TOKEN):

curl -X PUT -d '{"path": "testfile.txt", "message": "test", "content": "aGVsbG8y"}' https://api.github.com/repos/LOGIN/testrepo/contents/testfile.txt\?access_token\=TOKEN 

但在尝试对请求进行相同操作时,我一直遇到“解析 JSON 时出现问题”错误(状态代码 400):

data = { 
    "message": "test", 
    "content": "aGVsbG8y", 
    "path": "testfile.txt" 
} 
url = "https://api.github.com/repos/LOGIN/testrepo/contents/testfile.txt?access_token={}".format(TOKEN) 
response = requests.put(url, data=data) 

关于我的不同之处有什么提示吗?我检查了类似的问题,但没有找到正确的调整。谢谢!

请您参考如下方法:

因为只传递一个data 参数会自动将您的字典作为表单编码参数发送。而是将其作为 JSON 传递

import json 
data = { 
    "message": "test", 
    "content": "aGVsbG8y", 
    "path": "testfile.txt" 
} 
url = "https://api.github.com/repos/LOGIN/testrepo/contents/testfile.txt?access_token={}".format(TOKEN) 
response = requests.put(url, data=json.dumps(data)) 

或者,如果您至少使用 2.4.2 版,您可以这样做:

response = requests.put(url, json=data)