2017-06-22 38 views
0

我有兩個json文件,格式如下。我的目標是將它們結合起來,保持完全相同的格式 - 基本上疊加一個。結合json文件和保存格式在R

我曾嘗試以下,但這並不正確合併這兩個文件並保存格式,這兩個文件與[ ]分別括號。如何在整個文件中組合並保留一對括號?

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

可以使用在寫之前加入他們的行列rbind

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