Trying to turn a data frame into hierarchical json array using jsonlite in r

后端 未结 1 1968
隐瞒了意图╮
隐瞒了意图╮ 2021-01-21 04:42

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                


        
1条回答
  •  迷失自我
    2021-01-21 05:02

    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=),
              results=list(
                           list(id=),
                           list(id=),
                           ...)),
         ...)
    

    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)
    

    0 讨论(0)
提交回复
热议问题