jeroen/jsonlite

Question: Pass-through of character vectors of valid json in toJSON()?

thohan88 opened this issue · 2 comments

First of all, thank you so much for the excellent jsonlite-package.

I often deal with JSON-objects as large strings from databases such as this minimal example:

example <- data.frame(
  foo = c("bar", "bar"),
  json = c('{"foo": "bar"}', '{"foo": "bar"}') 
)
example
#>   foo           json
#> 1 bar {"foo": "bar"}
#> 2 bar {"foo": "bar"}

Naturally, if I convert this through toJSON() or stream_out(), json is outputted as a character as expected:

jsonlite::toJSON(example, pretty = TRUE)
#> [
#>   {
#>     "foo": "bar",
#>     "json": "{\"foo\": \"bar\"}"
#>   },
#>   {
#>     "foo": "bar",
#>     "json": "{\"foo\": \"bar\"}"
#>   }
#> ]

Usually, I need the conversion to JSON-data, so I do:

example$json <- lapply(example$json, jsonlite::fromJSON)
jsonlite::toJSON(example, auto_unbox = TRUE, pretty = TRUE)
#> [
#>   {
#>     "foo": "bar",
#>     "json": {
#>       "foo": "bar"
#>     }
#>   },
#>   {
#>     "foo": "bar",
#>     "json": {
#>       "foo": "bar"
#>     }
#>   }
#> ]

This works fine, but can take quite some time when the number and size of JSON-objects are large.

Is there a simpler option here that I am not seeing, e.g. enabling a pass through of valid character vectors of json in toJSON()?

Thanks again!

Not sure I fully get your question, but iiuc you want to the entire data from your database into json, keeping the data that is already in json format as-is?

Something like this?

example <- data.frame(
  foo = c("bar", "bar"),
  json = c('{"foo": "bar"}', '{"foo": "bar"}') 
)
class(example$json) <- 'json'

# json_verbatim passes through existing json strings
jsonlite::toJSON(example, json_verbatim=TRUE)

This is exactly what i was looking for - thanks a lot for the quick response!