我正在使用R包httr发送POST请求。我知道需求的主体应该是什么样子,但是我无法使用httr来创建它。我总是缺少一对方括号(见下文)。
如何修改我的R代码以获得所需的结果?
这是R POST代码段
cells <- c("Dimensions('Time')/Hierarchies('Time')/Elements('ABC')",
"Dimensions('Currency')/Hierarchies('Currency')/Elements('USD')")
value <- 123
with_verbose(
httr::POST(
url = url,
config = httr::config(ssl_verifypeer = FALSE, ssl_verifyhost = FALSE),
body = list(Cells = list(`Tuple@odata.bind` = cells), Value = value),
content_type("application/json"),
encode = "json",
set_cookies(...),
handle = handle
) %>% httr::content()
)
需要发送的正文:
{
"Cells":[
{"Tuple@odata.bind":[
"Dimensions('Time')/Hierarchies('Time')/Elements('ABC')",
"Dimensions('Currency')/Hierarchies('Currency')/Elements('USD')"
]}
],
"Value":"123"
}
发送的实际正文:
{
"Cells": ######### Missing bracket here #######
{"Tuple@odata.bind":[
"Dimensions('Time')/Hierarchies('Time')/Elements('ABC')",
"Dimensions('Currency')/Hierarchies('Currency')/Elements('USD')"
]},
####### Missing bracket here #######
"Value":"123"
}
答案 0 :(得分:1)
您快到了,只需向Cells
添加另一级列表:
library(magrittr)
library(jsonlite)
cells <- c("Dimensions('Time')/Hierarchies('Time')/Elements('ABC')",
"Dimensions('Currency')/Hierarchies('Currency')/Elements('USD')")
value <- 123
list(Cells = list(`Tuple@odata.bind` = cells), Value = value) %>%
toJSON() %>%
prettify()
#> {
#> "Cells": {
#> "Tuple@odata.bind": [
#> "Dimensions('Time')/Hierarchies('Time')/Elements('ABC')",
#> "Dimensions('Currency')/Hierarchies('Currency')/Elements('USD')"
#> ]
#> },
#> "Value": [
#> 123
#> ]
#> }
#>
list(Cells = list(list(`Tuple@odata.bind` = cells)), Value = value) %>%
toJSON() %>%
prettify()
#> {
#> "Cells": [
#> {
#> "Tuple@odata.bind": [
#> "Dimensions('Time')/Hierarchies('Time')/Elements('ABC')",
#> "Dimensions('Currency')/Hierarchies('Currency')/Elements('USD')"
#> ]
#> }
#> ],
#> "Value": [
#> 123
#> ]
#> }
#>
由reprex package(v0.2.1)于2018-09-23创建