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

R - Create a nested JSON object with two names from two different dataframes

有两个像

这样的数据框

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

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

只需将 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
#   }
#   ]
# }