Reputation: 168
I wish to export a few strings from R into a JSON file. However, I do not want to have the quotation marks around a certain dictionary like string while exporting the file.
For example
Here are the items I am trying to write to a JSON file.
x <- c("apples", "oranges")
y <- "{'add': 'bananas'}"
z <- list("mangoes", "pears")
full_line <- c(x, y, z)
jsonlite::write_json(full_line, "output.json", pretty = T, auto_unbox = T)
I would like the string "{'add': 'bananas'}"
to be written to the file output.json
without quotes as follows
"apples"
"oranges"
{'add': 'bananas'}
["mangoes", "pears"]
How can I achieve this in R?
I am currently using the jsonlite
package and its function write_json
for this purpose.
So far I have tried putting the string inside the noquote
function as well as tried cat
and adding quote = F
in the writeJSON function. But none of them work for my purpose.
Upvotes: 0
Views: 189
Reputation: 263421
If you want to use cat
you will need to make your last item into a character value rather than having it as a list, since cat
does not handle lists, Then you could use sapply
to run cat
over the three (atomic) items with "\n" paste0
-ed after each,
x <- c("apples", "oranges")
y <- "{'add': 'bananas'}"
z <- '["mangoes", "pears"]'
full_line <- c(x, y, z)
sapply( paste0(full_line, sep="\n"), cat, file="~/out.txt", append=TRUE)
If the file was empty at the beginning of the operation, then you would get this:
apples
oranges
{'add': 'bananas'}
["mangoes", "pears"]
If you wstill want double quotes around apples
and oranges
, then you would need to make that explicit.
Upvotes: 1