How do I add characters to the beginning of each collapsed result of paste0?

I’m trying to construct the input json input for mongodb query.

I have a vector that contains ids

[1] "62708dc95baeeff0a37571ab" "62708dc95baeeff0a37571ac"

I want to create a JSON object that looks like this:

[1] [{\"oid\":\"62708dc95baeeff0a37571ab"},{\"oid\":\"62708dc95baeeff0a37571ab"}]

so far I have been only able to do this:

["{\"oid\":\"62708dc95baeeff0a37571ab,62708dc95baeeff0a37571ac\"}"]

using this line of code:

sprintf('{"oid":"%s"}', paste0(doc_list, collapse=",")) %>% jsonlite::toJSON()

>Solution :

x <- c("62708dc95baeeff0a37571ab", "62708dc95baeeff0a37571ac")
DF <- data.frame(oid = x)

library(jsonlite)
toJSON(DF)
#[{"oid":"62708dc95baeeff0a37571ab"},{"oid":"62708dc95baeeff0a37571ac"}] 

Leave a Reply