我正在尝试将一些 Python 代码转换为 Julia。这是Python代码:
url = "http://api.scb.se/OV0104/v1/doris/sv/ssd/START/BE/BE0101/BE0101G/BefUtvKon1749"
json = {
"query": [
{
"code": "Kon",
"selection": {
"filter": "item",
"values": [
"1",
"2"
]
}
},
{
"code": "ContentsCode",
"selection": {
"filter": "item",
"values": [
"000000LV"
]
}
}
],
"response": {
"format": "px"
}
}
r = requests.post(url=url, json=json)
下面是 Julia 代码,该代码不起作用,并带有此错误消息:
syntax: { } vector syntax is discontinued around path:8
top-level scope at population_data.jl:8
using DataFrames, DataFramesMeta, HTTP, JSON3
url = "http://api.scb.se/OV0104/v1/doris/sv/ssd/START/BE/BE0101/BE0101G/BefUtvKon1749"
json = {
"query": [
{
"code": "Kon",
"selection": {
"filter": "item",
"values": [
"1",
"2",
"1+2"
]
}
},
{
"code": "ContentsCode",
"selection": {
"filter": "item",
"values": [
"000000LV"
]
}
}
],
"response": {
"format": "px"
}
}
r = HTTP.post(url, json)
我尝试解决此问题的方法如下:
- 使用“””将 json 变量转换为字符串。
- 使用 JSON3.read() 将 JSON 字符串转换为 Julia 数据类型
- 将转换后的 JSON 字符串传递给 POST 请求。这会产生以下错误:
IOError(Base.IOError("read: connection reset by peer (ECONNRESET)", -54) during request(http://api.scb.se/OV0104/v1/doris/sv/ssd/START/BE/BE0101/BE0101G/BefUtvKon1749)
这些都不起作用,我什至不确定它是关于 JSON 格式的。可能是我向 POST 请求传递了错误的参数。我该怎么办?
最佳答案
解决此问题的一种方法是将参数构建为 native julia 数据结构,并使用 JSON
进行转换并将它们用作 PUT 请求的正文:
julia 中的字典是使用 Dict(key => value)
等语法构建的。数组是使用标准语法构建的:[a, b, c]
。与您的参数等效的 Julia native 数据结构如下所示:
params = Dict(
"query" => [
Dict("code" => "Kon",
"selection" => Dict(
"filter" => "item",
"values" => [
"1",
"2",
"1+2"
]),
),
Dict("code"=> "ContentsCode",
"selection" => Dict(
"filter" => "item",
"values" => [
"000000LV"
]),
),
],
"response" => Dict(
"format" => "px"
))
然后,您可以使用 JSON.json()
将其构建为字符串的 JSON 表示形式,并将其传递给 HTTP 请求:
using HTTP
using JSON
url = "http://api.scb.se/OV0104/v1/doris/sv/ssd/START/BE/BE0101/BE0101G/BefUtvKon1749"
# send the request
r = HTTP.request("POST", url,
["Content-Type" => "application/json"],
JSON.json(params))
# retrieve the response body as a string
b = String(r.body)
关于json - Julia 中的 API POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64936578/