R - 使用来自两个不同数据帧的两个名称创建嵌套的JSON对象

时间:2016-02-17 21:24:09

标签: json r jsonlite

有两个数据框,如

final_data2:

      id type lang div
1   hola page   es   1

路径:

  source target count
1   hola  adios     1

我可以使用jsonlite和以下代码将两个数据帧组合在同一个JSON中:

cat(toJSON(c(apply(final_data2,1,function(x)list(id = unname(x[1]), 
type = unname(x[2]), lang = unname(x[3]), div = unname(x[4]))),
apply(paths,1,function(x)list(source = unname(x[1]), target = unname(x[2]),
playcount = unname(x[3])))), pretty = TRUE))

结果是一组数组如下:

[
  {
    "id": ["hola"],
    "type": ["page"],
    "lang": ["es"],
    "div": ["1"]
  },
  {
    "source": ["hola"],
    "target": ["adios"],
    "playcount": ["1"]
  }
]

但是,我需要生成的对象包含两个名称(nodeslinks),每个名称都嵌套一个先前定义的数据帧。因此,结构应如下所示:

{
  "nodes": [
    {
        "id": ["hola"],
        "type": ["page"],
        "lang": ["es"],
        "div": ["1"]
    }
  ],
  "links": [
    {
        "source": ["hola"],
        "target": ["adios"],
        "playcount": ["1"]
    }
  ]
}

关于如何实现它的任何提示?

1 个答案:

答案 0 :(得分:1)

只需将data.frames作为命名列表传递到toJSON

library(jsonlite)

df1 <- read.table(textConnection("      id type lang div
1   hola page   es   1"), header = T)
df2 <- read.table(textConnection("  source target count
1   hola  adios     1"), header = T)


toJSON(list(nodes = df1, links = df2), pretty = T)
# {
# "nodes": [
#   {
#     "id": "hola",
#     "type": "page",
#     "lang": "es",
#     "div": 1
#   }
#   ],
# "links": [
#   {
#     "source": "hola",
#     "target": "adios",
#     "count": 1
#   }
#   ]
# }