【问题标题】:Change structure data to write to JSON更改结构数据以写入 JSON
【发布时间】:2021-03-02 20:17:43
【问题描述】:

您好,我想更改我写入 JSON 的数据结构,但我不确定如何。

这是我的代码:

test_df <- data.frame(Metric = c("test1",
                                 "test2",
                                 "test3",
                                 "test4",
                                 "test5"),
                      Value = c(tail(test1$v, 1), 
                                tail(test2$v, 1),
                                tail(test3$v, 1),
                                tail(test4$v, 1),
                                tail(test5$v, 1)))
                                              


test_df_list <- list(test_df)

names(test_df_list) <- "test_df_df"

test_df_exportJSON <- toJSON(test_df_list, pretty = TRUE)

write(test_df_exportJSON, "test_df.json") 

结果:

{
  "test_df": [
    {
      "Metric": "test1",
      "Value": 47
    },
    {
      "Metric": "test2",
      "Value": 0.85
    },
    {
      "Metric": "test3",
      "Value": 0.98
    },
    {
      "Metric": "test4",
      "Value": 137
    },
    {
      "Metric": "test5",
      "Value": 2.1
    }
  ]
}

但我希望将 [] 删除,例如:

{
  "test_df": 
    {
      "test1": 47,
      "test2": 0.85,
       "test3": 0.98,
       "test4": 137,
       "test5": 2.1
    }
}

知道怎么做吗?任何帮助都会很棒!

不知何故,我收到消息“您的帖子似乎主要是代码;请添加更多详细信息”,因此请忽略此行以使其被接受;)

【问题讨论】:

    标签: r json brackets dataformat


    【解决方案1】:

    您可以在创建列表时删除Metric,稍后将其作为名称添加到列表元素中。还将Value 拆分为单个列表项。由于手头没有您的test1 数据,我在下面创建了一个示例。

    library(jsonlite)
    test_df <- data.frame(Metric = c('test1','test2','test3','test4','test5'),
                          Value = c(4,6,2,8,7))
    
    names <- as.vector(test_df$Metric)
    
    test_df_list <- structure(split(test_df$Value, seq(nrow(test_df))), names = names)
    
    test_df_list <- list(test_df = test_df_list)
    
    toJSON(test_df_list, pretty = TRUE, auto_unbox = TRUE)
    

    会给

    {
      "test_df": {
        "test1": 4,
        "test2": 6,
        "test3": 2,
        "test4": 8,
        "test5": 7
      }
    } 
    

    如果您来自toJSON()remove auto_unbox = TRUE,则值将在方括号中[ ].
    这对我有用,但也许有人想出了更方便的解决方案。

    【讨论】:

    • 是的!作品!谢谢!
    • @H.berg 很高兴知道这有效! jsonlite 或其他包的转换方式将始终取决于您的数据框或列表的结构。但有时很难找到正确的结构。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-17
    • 2022-11-12
    • 1970-01-01
    • 2016-06-05
    • 2015-04-07
    相关资源
    最近更新 更多