繁体   English   中英

从 R 中的 JSON 文件中删除方括号

[英]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_unboxjsonlite::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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM