将名称列为JSON对象名称

时间:2017-11-14 12:19:00

标签: r dplyr jsonlite

我正面临R中的JSON对象命名问题。

 df = list(`Choose to and fro flights` =  data.frame(sec =c('15:31:36' ,'15:31:37'),label=c("Choose to and fro flights","Choose to and fro flights"),responseCode = c( 200, 200), Counting=c(9,1)),
 `Details` = data.frame(sec = c("15:31:37" ,"15:31:37","15:31:38","15:31:39"),label = c("Details","Details","Details","Details"),responseCode = c("200","Non HTTP response code: org.apache.http.NoHttpResponseException","200","200"), Counting=c(2,2,5,1)))

我希望标签名称与此处的JSON对象名称相同 我正在尝试使用以下代码,但它没有给出正确答案

toJSON(list(ResponseCode=lapply(seq_along(df), function(i) {    list(R_C_seconds=df[[i]]$sec,R_C_labels=df[[i]]$label,R_C_responseCode=df[[i]]$responseCode,R_C_Count=df[[i]]$Counting)})))

是我的输出:

i want replace the label names in ***0*** and ***1*** positions

我想用标签名称替换 0 1

1 个答案:

答案 0 :(得分:2)

如果原始参数具有名称,则

lapply()在结果上设置名称。因此,您需要构建一个这样的命名向量,而不是seq_along(df)

idx <- seq_along(df)
names(idx) <- names(df)

或者您可以将df本身传递给lapply()


reprex::reprex_info()
#> Created by the reprex package v0.1.1.9000 on 2017-11-14

df <- list(
  `Choose to and fro flights` =  data.frame(sec = c('15:31:36', '15:31:37'),
                                            label = c("Choose to and fro flights", "Choose to and fro flights"),
                                            responseCode = c( 200, 200),
                                            Counting = c(9,1)),
  `Details` = data.frame(sec = c("15:31:37", "15:31:37", "15:31:38", "15:31:39"),
                         label = c("Details", "Details", "Details", "Details"),
                         responseCode = c("200", "Non HTTP response code: org.apache.http.NoHttpResponseException", "200", "200"),
                         Counting=c(2,2,5,1))
)


jsonlite::toJSON(
  list(
    ResponseCode = lapply(df, function(x) {
      list(
        R_C_seconds      = x$sec,
        R_C_labels       = x$label,
        R_C_responseCode = x$responseCode,
        R_C_Count        = x$Counting
      )
    })
  ),
  pretty = TRUE
)
#> {
#>   "ResponseCode": {
#>     "Choose to and fro flights": {
#>       "R_C_seconds": ["15:31:36", "15:31:37"],
#>       "R_C_labels": ["Choose to and fro flights", "Choose to and fro flights"],
#>       "R_C_responseCode": [200, 200],
#>       "R_C_Count": [9, 1]
#>     },
#>     "Details": {
#>       "R_C_seconds": ["15:31:37", "15:31:37", "15:31:38", "15:31:39"],
#>       "R_C_labels": ["Details", "Details", "Details", "Details"],
#>       "R_C_responseCode": ["200", "Non HTTP response code: org.apache.http.NoHttpResponseException", "200", "200"],
#>       "R_C_Count": [2, 2, 5, 1]
#>     }
#>   }
#> }