Fabian Gehring
Fabian Gehring

Reputation: 1173

Missing square brackets in body of POST request using R's httr package

I am using the R package httr to send a POST requests. I know how the body of the reqeust should look like, but I was not able to create it using httr. I am always missing a pair of square brackets (see below).

How do I have to modify my R code to get the desired result?

This is the R POST-snippet

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(`[email protected]` = cells), Value = value),
    content_type("application/json"),
    encode = "json",
    set_cookies(...),
    handle = handle
  ) %>% httr::content()
) 

desired body to be sent:

{
   "Cells":[
   {"[email protected]":[
      "Dimensions('Time')/Hierarchies('Time')/Elements('ABC')",
      "Dimensions('Currency')/Hierarchies('Currency')/Elements('USD')"
   ]}
   ],
   "Value":"123"
}

actual body that is sent:

{
   "Cells": ######### Missing bracket here #######
   {"[email protected]":[ 
      "Dimensions('Time')/Hierarchies('Time')/Elements('ABC')",
      "Dimensions('Currency')/Hierarchies('Currency')/Elements('USD')"
   ]},
   ####### Missing bracket here #######
   "Value":"123"
}

Upvotes: 2

Views: 374

Answers (1)

Birger
Birger

Reputation: 1141

You are almost there, just add another level of lists to Cells:

library(magrittr)
library(jsonlite)

cells <- c("Dimensions('Time')/Hierarchies('Time')/Elements('ABC')",
           "Dimensions('Currency')/Hierarchies('Currency')/Elements('USD')")
value <- 123

list(Cells = list(`[email protected]` = cells), Value = value) %>%
  toJSON() %>%
  prettify()
#> {
#>     "Cells": {
#>         "[email protected]": [
#>             "Dimensions('Time')/Hierarchies('Time')/Elements('ABC')",
#>             "Dimensions('Currency')/Hierarchies('Currency')/Elements('USD')"
#>         ]
#>     },
#>     "Value": [
#>         123
#>     ]
#> }
#> 

list(Cells = list(list(`[email protected]` = cells)), Value = value) %>%
  toJSON() %>%
  prettify()
#> {
#>     "Cells": [
#>         {
#>             "[email protected]": [
#>                 "Dimensions('Time')/Hierarchies('Time')/Elements('ABC')",
#>                 "Dimensions('Currency')/Hierarchies('Currency')/Elements('USD')"
#>             ]
#>         }
#>     ],
#>     "Value": [
#>         123
#>     ]
#> }
#> 

Created on 2018-09-23 by the reprex package (v0.2.1)

Upvotes: 1

Related Questions