将Curl数组JSON Post转换为Python

2024-10-02 20:39:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力改变

curl -d '[[51.3, 13.4], [51.4, 13.3]]' -XPOST  -H 'Content-Type: application/json'  https://elevation.racemap.com/api

Curl命令转换成Python。我试过了

import urllib.request
import json      

body = {'locs': [[51.3, 13.4], [51.4, 13.3]]}
myurl = "https://elevation.racemap.com/api"
req = urllib.request.Request(myurl)
req.add_header('Content-Type', 'application/json; charset=utf-8')
jsondata = json.dumps(body)
jsondataasbytes = jsondata.encode('utf-8')   
req.add_header('Content-Length', len(jsondataasbytes))
print (jsondataasbytes)
response = urllib.request.urlopen(req, jsondataasbytes)

这就产生了一个错误。似乎curl在传递数组时没有指定参数名?我不知道如何形成Json来适应curl输入。你知道吗


Tags: httpsimportcomapijsonapplicationrequesttype
1条回答
网友
1楼 · 发布于 2024-10-02 20:39:55

我只想用^{}

import requests

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

data = '[[51.3, 13.4], [51.4, 13.3]]'

response = requests.post('https://elevation.racemap.com/api', headers=headers, data=data)

print(response.status_code)
# 200

相关问题 更多 >