首页 > 解决方案 > 避免对具有 1 个值的向量进行拆箱

问题描述

对于我希望将数据推送到的 API,我需要避免在特定值上发生拆箱。

考虑以下输入:

library(jsonlite)

lsA <- list(propertyName = "listA",
            Values = c("x"))

lsB <- list(propertyName = "listB",
            Values = c("a","b","c"))

lsC <- list(propertyName = "listC",
            min = 1,
            max = 3)

我希望我的输出是这样的:

[
  {
    "propertyName": "listA",
    "Values": ["x"]
  },
  {
    "propertyName": "listB",
    "Values": ["a", "b", "c"]
  },
  {
    "propertyName": "listC",
    "min": 1,
    "max": 3
  }
] 

但是,当我这样做时:

lsTest <- list()
lsTest <- list.append(lsTest,I(lsA),lsB,lsC)

jsonTest <- jsonlite::toJSON(lsTest,auto_unbox = TRUE, pretty = TRUE)
jsonTest

我得到了这个(注意 listA 的未装箱值):

[
  {
    "propertyName": "listA",
    "Values": "x"
  },
  {
    "propertyName": "listB",
    "Values": ["a", "b", "c"]
  },
  {
    "propertyName": "listC",
    "min": 1,
    "max": 3
  }
]

如何避免在 toJSON 转换期间拆箱特定的单元素向量?

编辑: cwthom 好心解决了它。只需更改c("x")list("x"). 它也适用于包含多个项目的列表,并且只添加一些额外的新行,这似乎只是化妆品,对我的最终结果没有任何负面影响。

标签: rjsonliteunboxing

解决方案


推荐阅读