R到JSON:嵌入数组时遇到麻烦

时间:2018-07-21 01:06:40

标签: r json jsonlite

我正在使用jsonlite将一些数据从R转换为JSON。

所需的输出如下:

[
  {
    "data": {
      "name": "foo",
      "moogs": [
        {
          "x": 1,
          "y": 2
        },
        {
          "x": 2,
          "y": 1
        }
      ]
    }
  }
]

我正在为moogs处理嵌入式数组值。我最接近解决方案的是对其进行序列化:

[
  {
    "data": {
      "name": "foo",
      "moogs": "[{\"x\":1,\"y\":2},{\"x\":2,\"y\":1}]"
    }
  }
]

数据来自foo.R

name = "foo"

mtx = matrix(rep(0, 4), ncol=2, nrow=2)
mtx[1, 2] = 1
mtx[2, 1] = 1

该转换执行以下操作:

library(jsonlite)
source("foo.R")

moogs = data.frame()
for(x in 1:nrow(mtx)) {
  for(y in 1:ncol(mtx)) {
    if(mtx[x, y] == 1) {
      moogs = rbind(moogs, data.frame(x=x, y=y))
    }
  }
}

data = fromJSON('[{}]')
data$name = name
data$moogs = toJSON(moogs)

container = fromJSON('[{}]')
container$data = data

print(toJSON(container, pretty=TRUE))

如果我改变

data$moogs = toJSON(moogs)

data$moogs = moogs

我收到以下错误:

Error in `$<-.data.frame`(`*tmp*`, moogs, value = list(x = 1:2, y = 2:1)) :
  replacement has 2 rows, data has 1

有可能生产嵌入式阵列吗?

2 个答案:

答案 0 :(得分:3)

如果用列表(和数据框,即列表)模拟嵌套,则可以创建一个可以直接转换的R对象:

mtx <- matrix(c(0, 1, 1, 0), 2, dimnames = list(NULL, c('x', 'y')))
mtx
#>      x y
#> [1,] 0 1
#> [2,] 1 0

x <- list(data = list(name = 'foo', moogs = as.data.frame(mtx)))
str(x)
#> List of 1
#>  $ data:List of 2
#>   ..$ name : chr "foo"
#>   ..$ moogs:'data.frame':    2 obs. of  2 variables:
#>   .. ..$ x: num [1:2] 0 1
#>   .. ..$ y: num [1:2] 1 0

jsonlite::toJSON(x, auto_unbox = TRUE, pretty = TRUE)
#> {
#>   "data": {
#>     "name": "foo",
#>     "moogs": [
#>       {
#>         "x": 0,
#>         "y": 1
#>       },
#>       {
#>         "x": 1,
#>         "y": 0
#>       }
#>     ]
#>   }
#> }

答案 1 :(得分:1)

您需要带有列表列的数据框。做:

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.section == 1) {
        UICollectionViewCell *cell = [[UICollectionView alloc] init];  //create a normal cell
        [cell addSubview:anotherVC.view];
        return cell;
    }
}

然后:

data = data.frame(name=name, moogs=I(list(moogs))) 
container = data.frame(data = I(data))