File: read_json.R

package info (click to toggle)
r-cran-jsonlite 1.9.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,340 kB
  • sloc: ansic: 3,792; sh: 9; makefile: 6
file content (38 lines) | stat: -rw-r--r-- 1,183 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#' Read/write JSON
#'
#' These functions are similar to [toJSON()] and [fromJSON()] except they
#' explicitly distinguish between path and literal input, and do not simplify
#' by default.
#'
#' @export
#' @rdname read_json
#' @param path file on disk
#' @param simplifyVector simplifies nested lists into vectors and data frames. See [fromJSON()].
#' @seealso [fromJSON()], [stream_in()]
#' @examples tmp <- tempfile()
#' write_json(iris, tmp)
#'
#' # Nested lists
#' read_json(tmp)
#'
#' # A data frame
#' read_json(tmp, simplifyVector = TRUE)
read_json <- function(path, simplifyVector = FALSE, ...){
  parse_json(file(path), simplifyVector = simplifyVector, ...)
}

#' @export
#' @rdname read_json
#' @param json string with literal json or connection object to read from
parse_json <- function(json, simplifyVector = FALSE, ...){
  parse_and_simplify(json, simplifyVector = simplifyVector, ...)
}

#' @export
#' @rdname read_json
#' @param x an object to be serialized to JSON
#' @param ... additional conversion arguments, see also [toJSON()] or [fromJSON()]
write_json <- function(x, path, ...) {
  json <- jsonlite::toJSON(x, ...)
  writeLines(json, path, useBytes = TRUE)
}