【问题标题】:Converting Curl Array JSON Post to Python将 Curl Array JSON Post 转换为 Python
【发布时间】:2019-04-25 10:43:18
【问题描述】:

我正在尝试转换

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 输入。

【问题讨论】:

  • “一个错误”是所有错误中最糟糕的,因为没有人可以帮助您。请添加详细的错误描述,包括完整的错误回溯。

标签: python json python-3.x curl post


【解决方案1】:

我只想使用requests:

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

【讨论】:

    猜你喜欢
    • 2023-03-20
    • 2016-03-21
    • 2021-07-08
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 2011-04-07
    • 2017-04-27
    • 2021-08-09
    相关资源
    最近更新 更多