尝试在R中使用jsonlite将数据框转换为分层json数组 [英] Trying to turn a data frame into hierarchical json array using jsonlite in r

查看:110
本文介绍了尝试在R中使用jsonlite将数据框转换为分层json数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将我的超简单数据框变得更加有用-在这种情况下为json数组. 我的数据看起来像

I'm trying to get my super-simple data frame into something a little more useful - a json array in this case. My data looks like


| 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
        }
    ]
}

]

关于如何实现这一目标的任何想法? 感谢您的帮助!

Any thoughts on how I can make that happen? Thanks for your help!

推荐答案

您的data.frame无法直接写入该格式. 为了获得所需的json,首先需要将data.frame转换为以下结构:

Your data.frame cannot be directly written into that format. In order to get the desired json, firstly you need to turn your data.frame into this structure:

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

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

Here's a way to apply the transformation to your example data:

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)

这篇关于尝试在R中使用jsonlite将数据框转换为分层json数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆