# Connections and Streaming

    library(RJSONIO)

`fromJSON()` 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 4

## File connections

    path <- system.file("sampleData", "usaPolygons.as", package = "RJSONIO")
    con <- file(path)
    parsed <- fromJSON(con)
    close(con)

    length(parsed)
    #> [1] 3082

## Parser callbacks

Callbacks can be used to observe parser events without building the default R object.

    events <- character()

    result <- fromJSON(path, function(type, value) {
      events <<- c(events, names(type))
      TRUE
    })

    result
    #> NULL
    head(events)
    #> [1] "ARRAY_BEGIN" "ARRAY_BEGIN" "FLOAT"       "FLOAT"       "FLOAT"
    #> [6] "FLOAT"

## 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 3

## Practical 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.