我正在尝试使用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}]
答案 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
返回一个数据帧,然后应使用order3
将rbind
添加为新行。然后,如果将此数据帧转换为JSON,它将返回您要查找的内容。
您不必将order3
从列表转换为数据框即可将其重新绑定为新行。在将数据框转换为JSON之前,无需将其转换为列表。