【问题标题】:Trying to turn a data frame into hierarchical json array using jsonlite in r尝试在 r 中使用 jsonlite 将数据框转换为分层 json 数组
【发布时间】:2014-08-22 21:01:05
【问题描述】:

我正在尝试将我的超级简单数据框变成更有用的东西——在这种情况下是一个 json 数组。 我的数据看起来像

| V1 | V2 | V3 | V4 | V5 | |-----------|------------|------------|-----------|- ----------| | 717374788 | 694405490 | 606978836 | 578345907 | 555450273 | | 429700970 | 420694891 | 420694211 | 420792447 | 420670045 |

我希望它看起来像

[
{
    "V1": {
        "id": 717374788
    },
    "results": [
        {
            "id": 694405490
        },
        {
            "id": 606978836
        },
        {
            "id": 578345907
        },
        {
            "id": 555450273
        }
    ]
},
{
    "V1": {
        "id": 429700970
    },
    "results": [
        {
            "id": 420694891
        },
        {
            "id": 420694211
        },
        {
            "id": 420792447
        },
        {
            "id": 420670045
        }
    ]
}

]

关于如何实现这一点有什么想法吗? 感谢您的帮助!

【问题讨论】:

  • 为什么说“使用jsonlite”?为什么不写一两个循环和cat 输出呢?我怀疑使用 toJSON 生成输出所需的嵌套列表结构的代码与原始 loop-n-print 解决方案一样复杂。
  • 您能否将 dput 的输出粘贴到您的数据框中,以便我们可以处理一些事情?此外,向后工作。获取您想要的 JSON,使用 fromJSON 读取 INTO R,然后在混合数据框后为您提供所需的数据格式以使用 toJSON 生成所需的 JSON。

标签: json r jsonlite


【解决方案1】:

您的data.frame 无法直接写入该格式。 为了得到想要的 json,首先你需要把你的 data.frame 变成这个结构:

list(
     list(V1=list(id=<num>),
          results=list(
                       list(id=<num>),
                       list(id=<num>),
                       ...)),
     ...)

这是一种将转换应用于示例数据的方法:

library(jsonlite)
# recreate your data.frame
DF <- 
data.frame(V1=c(717374788,429700970),
           V2=c(694405490, 420694891),
           V3=c(606978836,420694211),
           V4=c(578345907,420792447),
           V5=c(555450273,420670045))

# transform the data.frame into the described structure
idsIndexes <- which(names(DF) != 'V1')
a <- lapply(1:nrow(DF),FUN=function(i){ 
                             list(V1=list(id=DF[i,'V1']),
                                  results=lapply(idsIndexes,
                                                FUN=function(j)list(id=DF[i,j])))
                           })

# serialize to json
txt <- toJSON(a)
# if you want, indent the json
txt <- prettify(txt)

【讨论】:

    猜你喜欢
    • 2021-07-11
    • 2018-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-22
    • 2015-04-14
    • 1970-01-01
    相关资源
    最近更新 更多