Connections and Streaming
Source:vignettes/connections-and-streaming.Rmd
connections-and-streaming.RmdfromJSON() can read from files and R connections.
readJSONStream() provides a lower-level connection-oriented
parser interface.
File paths
path <- system.file("sampleData", "keys.json", package = "RJSONIO")
parsed <- fromJSON(path)
names(parsed)
#> [1] "menu"Text connections
con <- textConnection("[1, 2, 3,\n4]")
parsed <- fromJSON(con)
close(con)
parsed
#> [1] 1 2 3 4File connections
path <- system.file("sampleData", "usaPolygons.as", package = "RJSONIO")
con <- file(path)
parsed <- fromJSON(con)
close(con)
length(parsed)
#> [1] 3082Parser callbacks
Callbacks can be used to observe parser events without building the default R object.
Streaming parser
readJSONStream() accepts a connection and reads JSON
content from it.
tmp <- tempfile(fileext = ".json")
writeLines("[1, 2, 3]", tmp, useBytes = TRUE)
con <- file(tmp, open = "rb")
streamed <- readJSONStream(con)
close(con)
unlink(tmp)
streamed
#> [1] 1 2 3Practical notes
For ordinary package code, start with fromJSON() on a
string, file path, or connection. Use parser callbacks or
readJSONStream() when the application needs lower-level
control over parsing.