[英]removing square brackets from JSON file in R
我正在 R 中創建一個 JSON 文件:
test <- c(list(item1 = "TEXT",
item2 = as.array(list(start = 0,
end = 99))))
write_json(test, path = "test.json" , auto_unbox = TRUE , null = "null")
這導致:
{"item1":"INDIVIDUAL_AGE","item2":{"start":[0],"end":[99]}}
但是我需要結果是:
{"item1":"INDIVIDUAL_AGE","item2":{"start":0,"end":99}}
如何擺脫 item2 元素中的方括號?
對於auto_unbox
, jsonlite::toJSON
推薦unbox
:
auto_unbox: automatically 'unbox' all atomic vectors of length 1. It is
usually safer to avoid this and instead use the 'unbox'
function to unbox individual elements. An exception is that
objects of class 'AsIs' (i.e. wrapped in 'I()') are not
automatically unboxed. This is a way to mark single values as
length-1 arrays.
為此,我們可以使用rapply
:
library(jsonlite)
toJSON(
rapply(test, function(z) if (length(z) == 1L) unbox(z) else z,
how = "replace")
)
# {"item1":"TEXT","item2":{"start":0,"end":99}}
(也適用於write_json
。)
...雖然對我來說auto_unbox=TRUE
在這里不起作用似乎很奇怪。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.