R - JSONLITE 在 JSON 数组"parent elements"末尾添加回车符



我是R中操作json数组的新手。当我使用R包jsonlite将json数组用下面的代码写入.json文件时,我会在该文件的第一行打印整个json数组(reg是一个data.frame)。

rownames(reg) <- NULL
write(toJSON(reg), file = "test.json")

我希望能够在嵌套层次结构中的每个主("父")元素的末尾添加回车"\n",因此它看起来如下所示:

[{"val":"ID1","prop":{"Sub":{"val":"foo"}},
{"val":"ID2","prop":{"Sub":{"val":"bar"}}]

而不是:

[{"val":"ID1","prop":{"Sub":{"val":"foo"}},{"val":"ID2","prop":{"Sub":{"val":"bar"}}]

有人能帮我吗?

注意:我不想要"漂亮"的布局。我想要每个父元素/所有子元素属性一行。

这是一个示例数据帧

reg <- data.frame(value=c("ID1", "ID2", "ID3"), properties.Subject.value=c("http://example.org/ID1", "http://example.org/ID2", "http://example.org/ID3"), properties.Subject.properties.value=c("http://example.org/xID1", "http://example.org/xID2", "http://example.org/xID3"))
value    properties.Subject.value  properties.Subject.properties.value
ID1      http://example.org/ID1    http://example.org/xID1
ID2      http://example.org/ID2    http://example.org/xID2
ID3      http://example.org/ID3    http://example.org/xID3

根据您对新线的要求,我认为stream_out应该可以工作。

require(jsonlite)
output <- file("test.json")
stream_out(head(mtcars), con = output, verbose = TRUE)

输出

{"mpg":21,"cyl":6,"disp":160,"hp":110,"drat":3.9,"wt":2.62,"qsec":16.46,"vs":0,"am":1,"gear":4,"carb":4,"_row":"Mazda RX4"}
{"mpg":21,"cyl":6,"disp":160,"hp":110,"drat":3.9,"wt":2.875,"qsec":17.02,"vs":0,"am":1,"gear":4,"carb":4,"_row":"Mazda RX4 Wag"}
{"mpg":22.8,"cyl":4,"disp":108,"hp":93,"drat":3.85,"wt":2.32,"qsec":18.61,"vs":1,"am":1,"gear":4,"carb":1,"_row":"Datsun 710"}
{"mpg":21.4,"cyl":6,"disp":258,"hp":110,"drat":3.08,"wt":3.215,"qsec":19.44,"vs":1,"am":0,"gear":3,"carb":1,"_row":"Hornet 4 Drive"}
{"mpg":18.7,"cyl":8,"disp":360,"hp":175,"drat":3.15,"wt":3.44,"qsec":17.02,"vs":0,"am":0,"gear":3,"carb":2,"_row":"Hornet Sportabout"}
{"mpg":18.1,"cyl":6,"disp":225,"hp":105,"drat":2.76,"wt":3.46,"qsec":20.22,"vs":1,"am":0,"gear":3,"carb":1,"_row":"Valiant"}

?stream_out

因为解析巨大的JSON字符串既困难又低效,所以JSON流是使用缩小的JSON记录行(也称为ndjson)来完成的。这是非常标准的:JSON数据库(如dat或MongoDB)使用相同的格式导入/导出数据集。请注意,这意味着组合的总流本身不是有效的JSON;只有个别线路是。还要注意,因为换行符被用作分隔符,所以不允许使用经过修饰的JSON:JSON行必须缩小。在这方面,格式与JSON和toJSON有点不同,在toJSON中,所有行都是带有可选换行符的单个JSON结构的一部分。

最新更新