0

我在 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 元素中的方括号?

4

1 回答 1

0

对于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但在这里不起作用。

于 2022-01-10T14:48:28.690 回答