我如何解析和处理已经存在于数据框内的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"}]')
)
我想要将y
列中的原始JSON提取,格式化并分离为有序列,最好是library(jsonlite)
。
提前致谢!
答案 0 :(得分:7)
使用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()
或仅使用dplyr
和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))
所有返回相同的东西,所以挑选哪个对你最有意义。