JSON "body" 参数中的数组 httr::POST()

JSON array in "body" parameter of httr::POST()

我想使用 httr 包发送一个 post 请求,在正文中包含一些变量。

正文如果采用 JSON 格式会是什么样子:

{a:"1", b:"2", c:[{d:"3", e:"4"}]}

我尝试使用 httr::POST()

r <- POST("http://httpbin.org/post", body = list(a = 1, b = 2, c = list(d=3, e=4)))

我得到的错误:

Error in curl::handle_setform(handle, .list = req$fields) : 

Unsupported value type for form field 'c'.

我需要如何构建我的 POST() 语句才能以上述我想要的格式发送它?

编辑:在尝试@renny 的解决方案时(我添加了 verbose() 以提高可见性)即以下行

r <- POST("http://httpbin.org/post", body = json_array, encode="json", verbose())

我能够观察到输出中生成的 JSON 格式如下:

{"post":{"a":1,"b":2,"c":{"d":3,"e":4}}}

如您所见,"c" 变量周围没有 [],而是有一个 "post" 变量。以下是我想要的。

{"a":1,"b":2,"c":[{"d":3,"e":4}]}
library(httr)

 json_array <- list(
      post =  list(a = 1, b = 2, c = list(d=3, e=4))
    )

 r <- POST("http://httpbin.org/post", body = json_array, encode="json")

app_data <- content(r)

试试这个。 这可能会奏效!

所以我不得不使用的这个问题的解决方案是 body 参数中的 JSON 字符串。 例如,如果以下是正在考虑的 JSON 字符串:

json <- {"a":1,"b":2,"c":[{"d":3,"e":4}]}

我必须将此 JSON 字符串作为 "body" 参数的值传递给 httr::POST() 所以函数调用看起来像:

r <- POST(url=url, body=json, encode="json", verbose())

我知道这是一个老问题,但也许有人会像我一样在这里结束。问题是缺少 list.

要创建 json 数组而不是对象,列表必须未命名。所以在你的例子中:

> json_array <- list(a = 1, b = 2, c = list(list(d=3, e=4)))

> jsonlite::toJSON(json_array)
{"a":[1],"b":[2],"c":[{"d":[3],"e":[4]}]}

# auto_unbox extracts values from unnecessary arrays, not explicit lists
> jsonlite::toJSON(json_array, auto_unbox = T)
{"a":1,"b":2,"c":[{"d":3,"e":4}]} 

那么您将不需要使用 jsonlite,因为编码可以完成工作:

httr::POST("http://httpbin.org/post", body = json_array, encode="json")

返回响应

{
  "args": {}, 
  "data": "{\"a\":1,\"b\":2,\"c\":[{\"d\":3,\"e\":4}]}", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept": "application/json, text/xml, application/xml, */*", 
    "Accept-Encoding": "deflate, gzip", 
    "Content-Length": "33", 
    "Content-Type": "application/json", 
...
}