-1

Okay so my problem was already mentionend in several other threads, but I am not able to figure it out:

I wrote the following code:

  my_list <- list(
    list(ids = c(100,200,300))
  )
  names(my_list) <- "Example"
  
  responseList <- httr::POST(url = url_endpoint, 
                             body = my_list, encode = "json", httr::verbose())

The verbose function shows what is sent, in this case {"Example":{"ids":[100,200,300]}}

In a second case I execute the following code

  my_list <- list(
    list(ids = c(100))
  )
  names(my_list) <- "Example"
  
  responseList <- httr::POST(url = url_endpoint, 
                             body = my_list, encode = "json", httr::verbose())

which leads to {"Example":{"ids":100}}. The important difference are the missing brackets [], since 100 is seen as a single value (which it is). However the API expects those brackets and hence throws an error in this case.

I found this problem in the following thread: How to distinguish between an element and a vector of length 1 in R?

It seems that there is a difference between the R packages rjson, RJSONIO (and probably also jsonlite, which I think is used in the httr package - unfortunately I cannot find the source, so I might be wrong here).

Now the problem is that I do not use toJSON from any of these packages, but the encoding within httr::POST. And here the documentation states on the parameter encode: (https://www.rdocumentation.org/packages/httr/versions/1.4.4/topics/POST)

"For "json", parameters are automatically "unboxed" (i.e. length 1 vectors are converted to scalars). To preserve a length 1 vector as a vector, wrap in I()."

Now my question is: What exactly do I need to wrap in I().?

KidLu
  • 163
  • 8

1 Answers1

0

When finishing the question I realized its answer (at first I used I() within body):

  my_list <- list(
    list(ids = I(c(100)))
  )
  names(my_list) <- "Example"
  
  responseList <- httr::POST(url = url_endpoint, 
                             body = my_list, encode = "json", httr::verbose())
KidLu
  • 163
  • 8