如何解析和处理已经存在于数据框中的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)
。提前致谢!
最佳答案
使用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))
所有人都返回同一件事,所以选择哪个对您来说最有意义。