Extract, format and separate JSON already stored in a data frame column

后端 未结 1 2000
有刺的猬
有刺的猬 2021-01-01 04:32

How might I parse and process JSON that already lives inside a data frame?

Sample data:

df <- data.frame(
    id = c(\"x1\", \"x2\"), 
    y = c(         


        
相关标签:
1条回答
  • 2021-01-01 04:54

    Using jsonlite and the tidyverse:

    library(tidyverse)
    library(jsonlite)
    
    df %>% mutate(y = map(y, ~fromJSON(as.character(.x)))) %>% unnest()
    
    # Source: local data frame [6 x 3]
    # 
    #       id Property            Value
    #   <fctr>    <chr>            <chr>
    # 1     x1       94            Error
    # 2     x1       C1      Found Match
    # 3     x1       C2 Address Mismatch
    # 4     x2       81              XYZ
    # 5     x2       D1        Blah Blah
    # 6     x2       Z2   Email Mismatch
    

    or without purrr,

    df %>% rowwise() %>% mutate(y = list(fromJSON(as.character(y)))) %>% unnest()
    

    or with just dplyr and jsonlite,

    df %>% rowwise() %>% do(data.frame(id = .$id, fromJSON(as.character(.$y))))
    

    or with just base R and jsonlite,

    do.call(rbind, 
            Map(function(id, y){data.frame(id, fromJSON(as.character(y)))}, 
                df$id, df$y))
    

    All return the same thing, so pick which makes the most sense to you.

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