在 POST 请求中使用 JSON 数组

Using a JSON array in a POST request

我正在编写一个 API wrapper 来使用 httr 包查询英国邮政编码,当我使用 GET 请求时一切正常。在使用 POST 请求时,我有点不知所措。

API 的 documentation 是这样说的:

Accepts a JSON object containing an array of postcodes. Returns a list of matching postcodes and respective available data.

Accepts up to 100 postcodes.

POST https://api.postcodes.io/postcodes?q=[postcode]

Post Data

This method requires a JSON object containing an array of postcodes to be posted. E.g.

{ "postcodes" : ["PR3 0SG", "M45 6GN", "EX165BL"] }

我尝试了以下方法:

library(httr)

pc_json <- '{
  "postcodes" : ["PR3 0SG", "M45 6GN", "EX165BL"]
}'

r <- POST(paste0("https://api.postcodes.io/postcodes?q=", pc_json, encode = "json"))

但是 returns 这个:

$status 1 400

$error 1 "Invalid JSON submitted. You need to submit a JSON object with an array of postcodes or geolocation objects"

当我 trim 数组并使用它时,同样的情况会发生:

r <- POST("https://api.postcodes.io/postcodes?q=EX165BL")
content(r)

我阅读了类似的帖子 here and here,但它们并没有使我的问题更容易解决。

有什么解决办法吗?

你快到了,只需要将邮政编码格式化为列表并使用 POST 的 body 参数,然后编码为 json:

library(httr)

pc_json <- list(
  postcodes = c("PR3 0SG", "M45 6GN", "EX165BL")
)
res <- POST("https://api.postcodes.io/postcodes"
            , body = pc_json
            , encode = "json")
appData <- content(res)