2017-10-18 36 views
3

我有一个大的JSON文件(8 GB,800万个案例),但我只需要它的一个小样本。简单的stream_in不起作用,因为文件太大。大JSON文件的样本

为了解决这个问题,我想下面的代码:

books <- list("Books_5.json") 
books <- map(books, ~ stream_in(file(.x)) %>% sample_n(385)) 
books <- as.data.frame(books) 

的问题是,经过3万页[R停止在文件中读取,因为该文件是如此之大。任何想法如何获得该文件的385个案例的样本?

较小文件的示例。变量是相同的。

Variables: 9 
$ reviewerID  <chr> "AF50PEUSO9MSV", "A1L0TVAJ1TYE06", "A64NRL5OSR3KB", ... 
$ asin   <chr> "B0000A1G05", "B009SQQF9C", "B005HRT88G", "B00D5T3QK... 
$ reviewerName <chr> "Matthew J. Hodgkins", "TCG", "Me", "J. Lee", "A. Bu... 
$ helpful  <list> [<1, 1>, <0, 1>, <1, 1>, <0, 0>, <0, 0>, <0, 0>, <0... 
$ reviewText  <chr> "This is the lens that I always keep on my camera by... 
$ overall  <dbl> 5, 5, 5, 5, 5, 5, 5, 4, 5, 2, 5, 4, 5, 4, 5, 5, 3, 4... 
$ summary  <chr> "Great lens!", "I love them! What else can I say", "... 
$ unixReviewTime <int> 1370736000, 1404518400, 1387411200, 1385769600, 1379... 
$ reviewTime  <chr> "06 9, 2013", "07 5, 2014", "12 19, 2013", "11 30, 2... 
+1

你能提供一些示例数据吗? –

回答

2

如果你的文件每行一个情况下,你可以使用LaF包非常有效地做到这一点:

library(LaF) 
random_lines <- sample_lines(filename = "Books_5.json", 
    n = 385) 

你可能会再有线路改造成你需要的格式,但这种解决方案允许从大文件读取而不需要将所有内容读入内存。

编辑: 所得线转化成data.frame

do.call("rbind",lapply(random_lines, fromJSON)) 

这应该只要在JSON-对象中的字段仅包含单个值(即不嵌套的)工作。

+0

感谢您的回答,但我不知道如何将结果字符串再次转换回原始数据框。 – Hadsga

+0

如果不知道结果字符串是怎么样的,说不清楚...你试过'jsonlite :: fromJSON()'吗? –

+0

该文件看起来像这样: 'chr [1:385]“{\”reviewerID \“:\”A29BC531E6553J \“,\”asin \“:\”0812510011 \“,\”reviewerName \“:\”Richard Rivera \“,\”helpful \“| __truncated__ ...' – Hadsga