如何从 r 中的哈希创建 json

how to create json from hash in r

我是 R 的新手,已经花了至少一天的时间来解决这个问题。

我一直在尝试从 data.table 创建 json,我想在其中使用其中一个变量的值作为键,并将其值作为一个列表组合其他变量。我无法克服的障碍是使用变量的值作为键。

数据看起来像:

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 "  
    }  
]  

我试过:

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

给出:

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

这显然不太正确。

最后一次尝试是使用 hash 包,因为它大大简化了我想要的结构的创建,但是,它似乎不是 rjson 或 json 中受支持的对象精简版。我收到如下错误:

Erreur : No method for S4 class:hash

恕我直言,有时手工操作更容易 - 这意味着在这种情况下:使用 sprintf 构建 json:

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