Skip to contents

as_r() transforms JSON or NDJSON to an R object.

Usage

as_r(
  data,
  object_names = "asis",
  ...,
  n_records = Inf,
  verbose = FALSE,
  data_type = j_data_type(data)
)

Arguments

data

a character() JSON string or NDJSON records, or the name of a file or URL containing JSON or NDJSON, or an R object parsed to a JSON string using jsonlite::toJSON().

object_names

character(1) order data object elements "asis" (default) or "sort" before filtering on path.

...

passed to jsonlite::toJSON when data is an R object.

n_records

numeric(1) maximum number of NDJSON records parsed.

verbose

logical(1) report progress when parsing large NDJSON files.

data_type

character(1) type of data; one of "json", "ndjson", or a value returned by j_data_type().

Value

as_r() returns an R object.

Details

The as = "R" argument to j_query(), j_pivot(), and the as_r() function transform JSON or NDJSON to an R object. JSON and NDJSON can be a character vector, file, or url, or an R object (which is first translated to a JSON string). Main rules are:

  • JSON arrays of a single type (boolean, integer, double, string) are transformed to R vectors of the same length and corresponding type. A JSON scalar and a JSON vector of length 1 are represented in the same way in R.

  • If a JSON 64-bit integer array contains a value larger than R's 32-bit integer representation, the array is transformed to an R numeric vector. NOTE that this results in loss of precision for 64-bit integer values greater than 2^53.

  • JSON arrays mixing integer and double values are transformed to R numeric vectors.

  • JSON objects are transformed to R named lists.

The vignette reiterates this information and provides additional details.

Examples

## as_r()
as_r('[1, 2, 3]')       # JSON integer array -> R integer vector
#> [1] 1 2 3
as_r('[1, 2.0, 3]')     # JSON intger and double array -> R numeric vector
#> [1] 1 2 3
as_r('[1, 2.0, "3"]')   # JSON mixed array -> R list
#> [[1]]
#> [1] 1
#> 
#> [[2]]
#> [1] 2
#> 
#> [[3]]
#> [1] "3"
#> 
as_r('[1, 2147483648]') # JSON integer > R integer max -> R numeric vector
#> [1]          1 2147483648

json <- '{"b": 1, "a": ["c", "d"], "e": true, "f": [true], "g": {}}'
as_r(json) |> str()     # parsing complex objects
#> List of 5
#>  $ b: int 1
#>  $ a: chr [1:2] "c" "d"
#>  $ e: logi TRUE
#>  $ f: logi TRUE
#>  $ g: Named list()
identical(              # JSON scalar and length 1 array identical in R
    as_r('{"a": 1}'), as_r('{"a": [1]}')
)
#> [1] TRUE