简体   繁体   English

如何将 JSON 列转换为 R 中的列表

[英]How to convert JSON column to list in R

I have data set like this我有这样的数据集

 genres [{"id": 28, "name": "Action"}, {"id": 12, "name": "Adventure"}, {"id": 14, "name": "Fantasy"}, {"id": 878, "name": "Science Fiction"}] [{"id": 12, "name": "Adventure"}, {"id": 14, "name": "Fantasy"}, {"id": 28, "name": "Action"}] [{"id": 28, "name": "Action"}, {"id": 12, "name": "Adventure"}, {"id": 80, "name": "Crime"}] [{"id": 28, "name": "Action"}, {"id": 80, "name": "Crime"}, {"id": 18, "name": "Drama"}, {"id": 53, "name": "Thriller"}] [{"id": 28, "name": "Action"}, {"id": 12, "name": "Adventure"}, {"id": 878, "name": "Science Fiction"}] [{"id": 14, "name": "Fantasy"}, {"id": 28, "name": "Action"}, {"id": 12, "name": "Adventure"}] [{"id": 16, "name": "Animation"}, {"id": 10751, "name": "Family"}]

Now I want to populate a drop down list of Shiny application so I want to convert the column JSON to data table, I use apply functions but does not get desired result, can someone please help me out.现在我想填充 Shiny 应用程序的下拉列表,所以我想将列 JSON 转换为数据表,我使用了应用函数但没有得到想要的结果,有人可以帮我。

Code:代码:

lapply(dt, fromJSON(dt$genres))

I am new to R so it may be not best solution but here my finding which is working in my case, please let me know if any feedback我是 R 的新手,所以它可能不是最好的解决方案,但在这里我的发现适用于我的情况,如果有任何反馈,请告诉我

 genre <- raw$genres
 genreList <- lapply(genre,function(x) fromJSON(x))
 genreList <- genreList[sapply(genreList, function(x) as.numeric(dim(x)[1])) > 0]
 genreList <- genreList[!sapply(genreList, is.null)]
 finalGenre <- unique(Reduce(function(...) merge(..., all=T), genreList)) 

And the output和输出

      id            name
1     28          Action
2     53        Thriller
3  10769         Foreign
4     12       Adventure
5  10751          Family
6    878 Science Fiction
7     27          Horror
8     16       Animation
9     80           Crime
10    35          Comedy
11 10770        TV Movie
12    18           Drama
13    99     Documentary
14 10752             War
15 10402           Music
16 10749         Romance
17    14         Fantasy
18    37         Western
19    36         History
20  9648         Mystery

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM