您可以使用jsonlite 库,但是为了解析数据,您必须对字符串进行一些“调整”。假设您拥有df,如下所示
my_df <- data.frame(column_1 =
c('{"name":"John", "age":30, "car":null}',
'{"name":"Chuck", "car":"black", "age":25}',
'{"car":"blue", "age":54, "name":
"David"}')
)
您必须具有有效的json 格式才能正确解析数据。在本例中是array json 格式,因此数据必须有[ 和]。此外,每个元素必须用, 分隔。小心strings,每个都必须有"<string>"。 (您没有在示例中使用 blue 和 black 数据添加它)
考虑到这一点,我们现在可以编写一些代码:
# Base R
# Add "commas" to sep each element
new_json_str <- paste(my_df$column_1, collapse = ",")
# Add "brackets" to the string
new_json_str <- paste("[", new_json_str, "]")
# Parse the JSON string with jsonlite
jsonlite::fromJSON(new_json_str)
# With dplyr library
my_df %>%
pull(column_1) %>% # Get column as "vector"
paste(collapse = ",") %>% # Add "commas"
paste("[", . ,"]") %>% # Add "bracket" (`.` represents the current value, in this case vectors sep by ",")
jsonlite::fromJSON() # Parse json to df
# Result
# name age car
# 1 John 30 <NA>
# 2 Chuck 25 black
# 3 David 54 blue