将json对象追加到json数组

时间:2019-04-24 18:11:21

标签: r json jsonlite

我正在尝试使用jsonlite将json对象附加到现有的json数组中。我要附加的json对象是使用toJSON创建的。

例如:

library(jsonlite)

order1 <- list(a = 1, b = 2, c = 3)
order2 <- list(a = 4, b = 5, c = 6)

# step1 represents my already existing json array
step1 <- toJSON(list(order1, order2), auto_unbox = TRUE)
# [{"a":1,"b":2,"c":3},{"a":4,"b":5,"c":6}] 

# order3 is a list that I would like to append to the step1array
order3 <- list(a = 7, b = 8, c = 9)

我尝试过:

step2 <- toJSON(list(fromJSON(step1), order3), auto_unbox = TRUE)

但是不幸的是,这会喷出来:

[[{"a":1,"b":2,"c":3},{"a":4,"b":5,"c":6}],{"a":7,"b":8,"c":9}] 

我的预期结果是:

[{"a":1,"b":2,"c":3},{"a":4,"b":5,"c":6},{"a":7,"b":8,"c":9}] 

我想念什么?

修改

我确实使用rbind_pages解决了这个问题,但是效率似乎有些低下。如果有更好的解决方案,我会全力以赴:)

toJSON(rbind_pages(list(fromJSON(step1), data.frame(order3))))
# [{"a":1,"b":2,"c":3},{"a":4,"b":5,"c":6},{"a":7,"b":8,"c":9}] 

1 个答案:

答案 0 :(得分:2)

要做:

toJSON(rbind(fromJSON(step1), order3))

结果:

[{"a":1,"b":2,"c":3},{"a":4,"b":5,"c":6},{"a":7,"b":8,"c":9}]

fromJSON返回一个数据帧,然后应使用order3rbind添加为新行。然后,如果将此数据帧转换为JSON,它将返回您要查找的内容。

您不必将order3从列表转换为数据框即可将其重新绑定为新行。在将数据框转换为JSON之前,无需将其转换为列表。