简体   繁体   English

使用 toJson function 时处理列表和 arrays - 在 R

[英]dealing with lists and arrays when using toJson function - in R

I am working with a pre-specified API definition, which I need to adhere to:我正在使用预先指定的 API 定义,我需要遵守该定义:

"myTable": {
    "split": [
        {
            "total": 0,
            "perItem": [
                0,
                0,
                0
            ]
        }
    ]

the results from my function are a list (since I am using an apply):我的 function 的结果是一个列表(因为我使用的是申请):

Export
[[1]]
[[1]]$total
[1] 13

[[1]]$perItem
1 2 3 
5 7 0 

but when I convert this to.json, it is not the same format as the predefined API definition:但是当我将其转换为 .json 时,它与预定义的 API 定义的格式不同:

toJSON(Export)
[{"total":[13],"perPlan":[5,7,0]}] 

I was wondering how I can convert the output of the apply to have the predefined API?我想知道如何将应用程序的 output 转换为具有预定义的 API?

I tried converting this to array:我尝试将其转换为数组:

toJSON(array(Export), simplify = TRUE)
[{"total":[13],"perPlan":[5,7,0]}] 

but this still has the additional [] around the content of total.但这仍然有额外的[]围绕总计的内容。

According to the API specification your input should also "embed" your data into this split and mytable list, which can be done with:根据 API 规范,您的输入还应该将您的数据“嵌入”到这个 split 和 mytable 列表中,这可以通过以下方式完成:

Export <- list(list(total = 13,
                    perItem = c(5, 7, 0)))

for_JSON <- list(mytable = list(split = Export))

toJSON(for_JSON, simplify = TRUE, pretty = TRUE)

which gives:这使:

{
  "mytable": {
    "split": [
      {
        "total": 13,
        "perItem": [5, 7, 0]
      }
    ]
  }
} 

This looks like what the API wants.这看起来像 API 想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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