Question

I need to create a JSON string from R using toJSON. My issue is that part of the JSON should contain an empty JSON object {}. I thought list() would do it for me:

> fromJSON("{}")
list()
> toJSON(list())
[1] "[]"

[Scratches head]

Anybody know how to get a {} using toJSON? I am using a lib that does the encoding, so answers that do not use toJSON will not help me.

Thanks!

Was it helpful?

Solution

There are a number of packages that have toJSON and fromJSON functions.

Using rjson::fromJSON, '{}' is read in as a list of length 0, whereas RJSONIO::fromJSON reads in {} as a named list of length 0.

In either package, calling fromJSON on a named list will do what you want.

Clearly, RJSONIO is performing as you want it to do

RJSONIO::toJSON(RJSONIO::fromJSON('{}'))
## [1] '{}'

rjson::toJSON(rjson::fromJSON('{}'))
## [1] "[]"

If you use rjson then you will have to manually set the names of the list of length 0

rjson::toJSON(setNames(rjson::fromJSON('{}'), character(0)))
## [1] "{}"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top