Converts JSON to an R object.

from_json(json, simplify = TRUE, fill_na = FALSE, buffer_size = 1024)

Arguments

json

JSON to convert to R object. Can be a string, url or link to a file.

simplify

logical, if TRUE, coerces JSON to the simplest R object possible. See Details

fill_na

logical, if TRUE and simplify is TRUE, data.frames will be na-filled if there are missing JSON keys. Ignored if simplify is FALSE. See details and examples.

buffer_size

size of buffer used when reading a file from disk. Defaults to 1024

Details

When simplify = TRUE

  • single arrays are coerced to vectors

  • array of arrays (all the same length) are coerced to matrices

  • objects with the same keys are coerced to data.frames

When simplify = TRUE and fill_na = TRUE

  • objects are coerced to data.frames, and any missing values are filled with NAs

Examples


from_json('{"a":[1, 2, 3]}')
#> $a
#> [1] 1 2 3
#> 
from_json('{"a":8, "b":99.5, "c":true, "d":"cats", "e":[1, "cats", 3]}')
#> $a
#> [1] 8
#> 
#> $b
#> [1] 99.5
#> 
#> $c
#> [1] TRUE
#> 
#> $d
#> [1] "cats"
#> 
#> $e
#> [1] "1"    "cats" "3"   
#> 
from_json('{"a":8, "b":{"c":123, "d":{"e":456}}}')
#> $a
#> [1] 8
#> 
#> $b
#> $b$c
#> [1] 123
#> 
#> $b$d
#> $b$d$e
#> [1] 456
#> 
#> 
#> 

lst <- list("a" = 5L, "b" = 1.43, "c" = "cats", "d" = FALSE)
js <- jsonify::to_json(lst, unbox = TRUE)
from_json( js )
#> $a
#> [1] 5
#> 
#> $b
#> [1] 1.43
#> 
#> $c
#> [1] "cats"
#> 
#> $d
#> [1] FALSE
#> 

## Return a data frame
from_json('[{"id":1,"val":"a"},{"id":2,"val":"b"}]')
#>   id val
#> 1  1   a
#> 2  2   b

## Return a data frame with a list column
from_json('[{"id":1,"val":"a"},{"id":2,"val":["b","c"]}]')
#>   id  val
#> 1  1    a
#> 2  2 b, c

## Without simplifying to a data.frame
from_json('[{"id":1,"val":"a"},{"id":2,"val":["b","c"]}]', simplify = FALSE )
#> [[1]]
#> [[1]]$id
#> [1] 1
#> 
#> [[1]]$val
#> [1] "a"
#> 
#> 
#> [[2]]
#> [[2]]$id
#> [1] 2
#> 
#> [[2]]$val
#> [[2]]$val[[1]]
#> [1] "b"
#> 
#> [[2]]$val[[2]]
#> [1] "c"
#> 
#> 
#> 

## Missing JSON keys 
from_json('[{"x":1},{"x":2,"y":"hello"}]')
#> [[1]]
#> [[1]]$x
#> [1] 1
#> 
#> 
#> [[2]]
#> [[2]]$x
#> [1] 2
#> 
#> [[2]]$y
#> [1] "hello"
#> 
#> 

## Missing JSON keys - filling with NAs
from_json('[{"x":1},{"x":2,"y":"hello"}]', fill_na = TRUE )
#>   x     y
#> 1 1  <NA>
#> 2 2 hello

## Duplicate object keys
from_json('[{"x":1,"x":"a"},{"x":2,"x":"b"}]')
#>   x
#> 1 1
#> 2 2

from_json('[{"id":1,"val":"a","val":1},{"id":2,"val":"b"}]', fill_na = TRUE )
#>   id val
#> 1  1   a
#> 2  2   b