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

问题描述 投票:0回答:2

我想使用httr包发送一个带有一些变量的帖子请求。

如果它是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}]}
r post httr jsonlite
2个回答
1
投票
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)

试试这个。这可能会成功!


0
投票

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

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

我必须将此JSON字符串作为httr :: POST()的“body”参数的值传递,因此函数调用如下所示:

r <- POST(url=url, body=json, encode="json", verbose())
© www.soinside.com 2019 - 2024. All rights reserved.