首先,这是解析 json 数据的方法
# if you read the data in a table with 3 column and 1 line
tab <- data.frame(name = "Test1",
published_date = "1151367060",
ratings ="[{'id': 7, 'name': 'Funny', 'count': 19645}, {'id': 1, 'name': 'Beautiful', 'count': 4573}, {'id': 9, 'name': 'Ingenious', 'count': 6073}, {'id': 3, 'name': 'Courageous', 'count': 3253}, {'id': 11, 'name': 'Longwinded', 'count': 387}, {'id': 2, 'name': 'Confusing', 'count': 242}, {'id': 8, 'name': 'Informative', 'count': 7346}, {'id': 22, 'name': 'Fascinating', 'count': 10581}, {'id': 21, 'name': 'Unconvincing', 'count': 300}, {'id': 24, 'name': 'Persuasive', 'count': 10704}, {'id': 23, 'name': 'Jaw-dropping', 'count': 4439}, {'id': 25, 'name': 'OK', 'count': 1174}, {'id': 26, 'name': 'Obnoxious', 'count': 209}, {'id': 10, 'name': 'Inspiring', 'count': 24924}]",
stringsAsFactors = FALSE)
# Use jsonlite for parsing json
library(jsonlite)
# single quote is invalid, so if real, you need to replace them all by double quote
tab$ratings <- gsub("'", "\"", tab$ratings)
# parse the json
rating <- fromJSON(tab$ratings)
rating
#> id name count
#> 1 7 Funny 19645
#> 2 1 Beautiful 4573
#> 3 9 Ingenious 6073
#> 4 3 Courageous 3253
#> 5 11 Longwinded 387
#> 6 2 Confusing 242
#> 7 8 Informative 7346
#> 8 22 Fascinating 10581
#> 9 21 Unconvincing 300
#> 10 24 Persuasive 10704
#> 11 23 Jaw-dropping 4439
#> 12 25 OK 1174
#> 13 26 Obnoxious 209
#> 14 10 Inspiring 24924
您可以使用以下方法将此解析保留在输入表中
tidyverse 管道工作流和小标题。使用创建列表的能力
列,您可以将 fromJSON 结果存储在表中以代替 json 字符串
library(tidyverse)
tab %>%
# convert to tibble for nice printing
as_tibble() %>%
# work on ratings column
mutate(
# replace single quote
ratings = gsub("'", "\"", ratings),
# create a list column with the result
ratings= list(jsonlite::fromJSON(ratings))
) %>%
# unnest the list column
unnest()
#> # A tibble: 14 x 5
#> name published_date id name1 count
#> <chr> <chr> <int> <chr> <int>
#> 1 Test1 1151367060 7 Funny 19645
#> 2 Test1 1151367060 1 Beautiful 4573
#> 3 Test1 1151367060 9 Ingenious 6073
#> 4 Test1 1151367060 3 Courageous 3253
#> 5 Test1 1151367060 11 Longwinded 387
#> 6 Test1 1151367060 2 Confusing 242
#> 7 Test1 1151367060 8 Informative 7346
#> 8 Test1 1151367060 22 Fascinating 10581
#> 9 Test1 1151367060 21 Unconvincing 300
#> 10 Test1 1151367060 24 Persuasive 10704
#> 11 Test1 1151367060 23 Jaw-dropping 4439
#> 12 Test1 1151367060 25 OK 1174
#> 13 Test1 1151367060 26 Obnoxious 209
#> 14 Test1 1151367060 10 Inspiring 24924
由reprex package (v0.1.1.9000) 于 2018 年 1 月 14 日创建。