For an API I wish to push data to, I need to avoid unboxing to happen on specific values.
Consider the following input:
library(jsonlite)
lsA <- list(propertyName = "listA",
Values = c("x"))
lsB <- list(propertyName = "listB",
Values = c("a","b","c"))
lsC <- list(propertyName = "listC",
min = 1,
max = 3)
I want my output to be like this:
[
{
"propertyName": "listA",
"Values": ["x"]
},
{
"propertyName": "listB",
"Values": ["a", "b", "c"]
},
{
"propertyName": "listC",
"min": 1,
"max": 3
}
]
However, when I do this:
lsTest <- list()
lsTest <- list.append(lsTest,I(lsA),lsB,lsC)
jsonTest <- jsonlite::toJSON(lsTest,auto_unbox = TRUE, pretty = TRUE)
jsonTest
I'm getting this (notice the unboxed value for listA):
[
{
"propertyName": "listA",
"Values": "x"
},
{
"propertyName": "listB",
"Values": ["a", "b", "c"]
},
{
"propertyName": "listC",
"min": 1,
"max": 3
}
]
How can I avoid specific one-element vectors to be unboxed during the toJSON conversion?
EDIT: cwthom kindly resolved it. Just change c("x") to list("x"). It works for lists with multiple items as well, and only add some additional new lines, which appear to be cosmetics only and did not have any negative impact on the end result on my end.