合并json文件并保留R

时间:2017-06-22 02:02:36

标签: json r

我有两个json文件,格式如下。我的目标是将它们组合起来并保持完全相同的格式 - 基本上只将一个堆叠在另一个上面。

我尝试过以下操作,但这并未正确合并这两个文件并保留格式,因为这两个文件分别用[ ]括起来。如何在整个文件中组合并保留一对括号?

files <- c("test.json","test2.json")
jsonl <- lapply(files, function(f) fromJSON(file = f))
jsonc <- toJSON(jsonl)
write(jsonc, file = "two.json")

R中有更好的解决方案吗?

test.json

[
  {
    "vendor": 0,
    "startTime": 4380,
    "endTime": 4445
  },
  {
    "vendor": 0,
    "startTime": 4448,
    "endTime": 4453
  },
  {
    "vendor": 0,
    "startTime": 4696,
    "endTime": 4880
  }
]

不受欢迎的输出:

[
  [
    {"vendor":0,"startTime":4380,"endTime":4445},
    {"vendor":0,"startTime":4448,"endTime":4453},
    {"vendor":0,"startTime":4696,"endTime":4880}],

    [{"vendor":0,"startTime":4380,"endTime":4445},
      {"vendor":0,"startTime":4448,"endTime":4453},
      {"vendor":0,"startTime":4696,"endTime":4880}
  ]
]

期望的输出:

  [
    {"vendor":0,"startTime":4380,"endTime":4445},
    {"vendor":0,"startTime":4448,"endTime":4453},
    {"vendor":0,"startTime":4696,"endTime":4880},
    {"vendor":0,"startTime":4380,"endTime":4445},
    {"vendor":0,"startTime":4448,"endTime":4453},
    {"vendor":0,"startTime":4696,"endTime":4880}
  ]

1 个答案:

答案 0 :(得分:1)

您可以在使用rbind

写作之前加入他们
files <- c("test.json","test2.json")
jsonl <- do.call("rbind", lapply(files, function(f) fromJSON(f)))
write(toJSON(jsonl), file = "two.json")