【问题标题】:removing square brackets from JSON file in R从R中的JSON文件中删除方括号
【发布时间】:2022-01-10 14:42:17
【问题描述】:

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

【问题讨论】:

    标签: r arrays json list to-json


    【解决方案1】:

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

    【讨论】:

    • 有不同的方法吗?我只选择了我正在处理的 .JSON 的 sn-p,但是通过使用提供的解决方案,我必须将其应用于整个 JSON。
    • 我不知道其他方法。我认为auto_unbox=TRUE 将是规范的方式,但阅读帮助文档表明并非如此。坦率地说,我认为这是一个错误,应该作为一个错误提出。无论如何,您是否有理由不能在整个数据集上使用 rapply
    猜你喜欢
    • 1970-01-01
    • 2013-11-09
    • 2013-11-11
    • 1970-01-01
    • 2021-09-12
    • 2018-10-30
    • 2017-03-25
    • 2019-03-11
    • 1970-01-01
    相关资源
    最近更新 更多