在POST请求中使用JSON数组 [英] Using a JSON array in a POST request
问题描述
我正在编写一个API 包装,使用 httr <查询英国邮政编码/ code>包,当我使用
GET
请求时一切正常。在使用 POST
请求时,我有点迷失。
I'm writing an API wrapper to query UK postcodes using httr
package and everything works fine when I use GET
requests. I'm slightly lost when it comes to using a POST
request.
这是文档说:
接受a包含邮政编码数组的JSON对象。返回匹配邮政编码和相应可用数据的
列表。
Accepts a JSON object containing an array of postcodes. Returns a list of matching postcodes and respective available data.
最多可接受100个邮政编码。
Accepts up to 100 postcodes.
POST https://api.postcodes.io/postcodes?q=[postcode]
发布数据
此方法需要一个包含
的邮政编码数组的JSON对象被张贴。例如
This method requires a JSON object containing an array of postcodes to be posted. E.g.
{postcodes:[PR3 0SG,M45 6GN,EX165BL]}
{ "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"))
但它返回:
$ status 1 400
$ error 1 提交的JSON无效。您需要使用一组邮政编码或地理位置对象提交JSON对象
$error 1 "Invalid JSON submitted. You need to submit a JSON object with an array of postcodes or geolocation objects"
当我修剪数组并使用它时会发生同样的情况:
The same happens when I trim the array and use this:
r <- POST("https://api.postcodes.io/postcodes?q=EX165BL")
content(r)
我读过SIM卡ilar线程和 here ,但他们没有让我的问题更容易解决。
I read similar threads here and here, but they didn't make my problem any easier to solve.
任何想法如何修复它?
推荐答案
您几乎只需要将邮政编码格式化为列表并使用 POST
的body参数然后编码为 json
:
Your almost there just need to format the postcodes as a list and use the body argument of POST
then encode as 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)
这篇关于在POST请求中使用JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!