4

我如何解析和处理已经存在于数据框中的 JSON?

样本数据:

df <- data.frame(
    id = c("x1", "x2"), 
    y = c('[{"Property":"94","Value":"Error"},{"Property":"C1","Value":"Found Match"},{"Property":"C2","Value":"Address Mismatch"}]', '[{"Property":"81","Value":"XYZ"},{"Property":"D1","Value":"Blah Blah"},{"Property":"Z2","Value":"Email Mismatch"}]')
)

我想将列中的原始 JSON 提取、格式化和分离y成有序的列,最好使用library(jsonlite).

提前致谢!

4

1 回答 1

11

使用jsonlite和 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

或没有purrr

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

或者只有dplyrand jsonlite,

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

或仅使用基础 R 和jsonlite,

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

所有返回相同的东西,所以选择对你最有意义的。

于 2016-06-23T16:48:45.370 回答