0

am new to R and have already passed at least a day trying to figure this out.

I've been trying to create json from a data.table, where I'd like to use the value of one of the variables as a key, and as its value a list combining the other variables. The hurdle I have not been able to overcome is using the value of the variable as the key.

Data looks like:

x<-data.table(ipUnit=c("192.168.2.254/1","192.168.2.5/1"), ip=c("192.168.2.254","192.168.2.5"), unit=c("1","1"))

            ipUnit            ip unit  
1: 192.168.2.254/1 192.168.2.254    1  
2:   192.168.2.5/1   192.168.2.5    1  

JSON I'd like to eventually have:  

IP_UNIT_ID" : [  
    "192.168.2.254/1" : {  
        "IP_ADDR" : "192.168.2.254",  
        "UNIT_ID" : "1 "  
    },  
    "192.168.2.5/1" : {  
        "IP_ADDR" : "192.168.2.5",  
        "UNIT_ID" : "1 "  
    }  
]  

I've tried:

e=parse(text="list(IP_UNIT_ID(list(ipUnit=list(\"IP_ADDR\"=ip,\"UNIT_ID\"=unit) )))")
toJSON(x[,eval(e)])

which gives:

[{"IP_UNIT_ID":{"IP_ADDR":["192.168.2.254","192.168.2.5"],"UNIT_ID":["1","1"]}}] 

which apparently is not quite right.

Last attempt was to use the hash package as that greatly simplifies creating the structure I'd like, however, it does not seem to be a supported object in either rjson or jsonlite. I received errors such as:

Erreur : No method for S4 class:hash

lstilo
  • 5
  • 1
  • 4

1 Answers1

0

IMHO, sometimes it's easier to to things by hand - which means in this case: contructing the json using sprintf:

x<-data.frame(ipUnit=c("192.168.2.254/1","192.168.2.5/1"), ip=c("192.168.2.254","192.168.2.5"), unit=c("1","1"))
txt <- readLines(n = 10)
# "IP_UNIT_ID" : [
#     "192.168.2.254/1" : {
#         "IP_ADDR" : "192.168.2.254",
#         "UNIT_ID" : "1 "
#     },
#     "192.168.2.5/1" : {
#         "IP_ADDR" : "192.168.2.5",
#         "UNIT_ID" : "1 "
#     }
# ]
txt <- sub("# ", "", txt)
txt <- paste0(txt, collapse = "\n")
txt_ <- sprintf('"IP_UNIT_ID" : [\n%s\n]', paste0(with(x, sprintf('    "%s" : {\n        "IP_ADDR" : "%s",\n        "UNIT_ID" : "%s "\n    }', ipUnit, ip, unit, unit)), collapse = ",\n"))
identical(txt, txt_)
# [1] TRUE
lukeA
  • 53,097
  • 5
  • 97
  • 100