deschen
deschen

Reputation: 11016

R Apply a jsonlite::unbox command to a list

I want to communicate with an API that needs a certain format, see below:

library(jsonlite)
list(limits = list("Overall_Wave3/0" = unbox("14000"),
                   "Overall_Wave3/1" = unbox("14005")))

which gives (note the indexes of that list are [x]):

$limits
$limits$`Overall_Wave3/0`
[x] "14000"

$limits$`Overall_Wave3/1`
[x] "14005"

Now in my real life use case, I would need to create hundreds of such elements within a list, so I need to somehow automate things. My input will be a data frame (or tibble) that I need to put into that format. I get this working, however, only without successfully doing the unbox. I.e. here's how far I got:

library(tidyverse)
library(jsonlite)

dat <- data.frame(marker = c("Overall_Wave3/0", "Overall_Wave3/0"),
                  value  = c(14000, 14005)) %>%
  mutate(value = as.character(value))

args <- as.list(dat$value)
names(args) <- dat$marker

list(limits = args)

which gives (note that the indexes are now [1] instead of [x]:

$limits
$limits$`Overall_Wave3/0`
[1] "14000"

$limits$`Overall_Wave3/0`
[1] "14005"

Now converting both lists to a JSON body with toJSON(...) gives different results:

The second command has unnecessary squared brackets around the numbers that must not be there. I know I could probably do a hack with a string replace, but would strongly prefer a solution that works right from the start (if it can be done within the tidyverse, I wouldn't be too sad about it).

Thanks.

Upvotes: 0

Views: 154

Answers (0)

Related Questions