在python中执行curl请求

在python中执行curl请求,python,json,rest,curl,Python,Json,Rest,Curl,我正在尝试用python执行一个curl请求。我的代码如下: url = 'http://xx.xxx.xx.xxx:xxxx/api/common/learningSessions/588752bef1d4654173a43015' payload = json.loads(open("request.json")) headers = {'X-User-Path': '....', 'X-User-Token': '...') r = requests.

我正在尝试用python执行一个curl请求。我的代码如下:

url = 'http://xx.xxx.xx.xxx:xxxx/api/common/learningSessions/588752bef1d4654173a43015'          
payload = json.loads(open("request.json"))         
headers = {'X-User-Path': '....', 'X-User-Token': '...')
r = requests.get(url, data=json.dumps(payload), headers=headers)
然而,我在第二行收到以下错误:

TypeError:预期的字符串或缓冲区有效负载=json.loadsopenrequest.json

知道这个错误是怎么回事吗

应为字符串或缓冲区

打开返回一个文件

json.load和json.load之间有一个区别,第二个接受的是字符串,而不是文件

此外,我认为json.dumps是不必要的

您正在打开文件openrequest.json,它将返回

json.load需要字符串

你可以试试

url = 'http://xx.xxx.xx.xxx:xxxx/api/common/learningSessions/588752bef1d4654173a43015'          
payload = json.loads(open("request.json").read())         
headers = {'X-User-Path': '....', 'X-User-Token': '...')
r = requests.post(url, data=json.dumps(payload), headers=headers)
file.read将返回文件内容而不是文件对象

如果不想使用read,可以直接使用json.load而不是json.load

这就是我试过的

echo '{}' > /tmp/test.json
cat /tmp/test.json
{}
尝试读取相同的文件

Python 2.7.10 (default, Jul 30 2016, 19:40:32)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import json
>>> payload = json.loads(open("/tmp/test.json").read())
>>> print payload
{}
您正在使用但正在尝试加载文件。你需要改用


然后我在同一行中接收到:ValueError:无法创建JSON对象decoded@christosh那么您的json文件不是有效的json格式,请在一些验证器中检查其格式。我的json只包含{}。实际上我想执行get not post。然后我在同一行中收到:VALUETERROR:在同一行中无法解码JSON对象。@christosh您能给出您的文件内容吗?因为我在尝试payload=json.loadsopenrequest.json.read时尝试了示例json及其工作特性,所以我得到了相同的错误。创建一个test.json文件并将内容添加为{},那么这段代码就可以工作了。如果你能提供你的文件内容,我们可以提供更好的帮助。我的json只包含{}。实际上,我想执行get not post,但我的json是经过验证的。
payload = json.load(open("request.json"))