Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using RJSONIO and AsIs class

Tags:

json

text

r

I am writing some helper functions to convert my R variables to JSON. I've come across this problem: I would like my values to be represented as JSON arrays, this can be done using the AsIs class according to the RJSONIO documentation.

x = "HELLO"
toJSON(list(x = I(x)), collapse="")

"{ \"x\": [ \"HELLO\" ] }"

But say we have a list

y = list(a = "HELLO", b = "WORLD")
toJSON(list(y = I(y)), collapse="")

"{ \"y\": {\n \"a\": \"HELLO\",\n\"b\": \"WORLD\" \n} }"

The value found in y -> a is NOT represented as an array. Ideally I would have

"{ \"y\": [{\n \"a\": \"HELLO\",\n\"b\": \"WORLD\" \n}] }"

Note the square brackets. Also I would like to get rid of all "\n"s, but collapse does not eliminate the line breaks in nested JSON. Any ideas?

like image 298
JCWong Avatar asked Nov 22 '25 06:11

JCWong


1 Answers

try writing as

y = list(list(a = "HELLO", b = "WORLD"))
test<-toJSON(list(y = I(y)), collapse="")

when you write to file it appears as:

{ "y": [
 {
 "a": "HELLO",
"b": "WORLD" 
} 
] }

I guess you could remove the \n as

test<-gsub("\n","",test)

or use RJSON package

> rjson::toJSON(list(y = I(y)))
[1] "{\"y\":[{\"a\":\"HELLO\",\"b\":\"WORLD\"}]}"

The reason

> names(list(a = "HELLO", b = "WORLD"))
[1] "a" "b"
> names(list(list(a = "HELLO", b = "WORLD")))
NULL

examining the rjson::toJSON you will find this snippet of code

  if (!is.null(names(x))) 
            return(toJSON(as.list(x)))
        str = "["

so it would appear to need an unnamed list to treat it as a JSON array. Maybe RJSONIO is similar.

like image 74
shhhhimhuntingrabbits Avatar answered Nov 24 '25 20:11

shhhhimhuntingrabbits