File: read_json.R

package info (click to toggle)
r-cran-jsonlite 1.7.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 1,320 kB
  • sloc: ansic: 3,792; sh: 9; makefile: 2
file content (38 lines) | stat: -rw-r--r-- 1,218 bytes parent folder | download
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 \link{toJSON} and \link{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 \link{fromJSON}.
#' @seealso \code{\link{fromJSON}}, \code{\link{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 \link{toJSON} or \link{fromJSON}
write_json <- function(x, path, ...) {
  json <- jsonlite::toJSON(x, ...)
  writeLines(json, path, useBytes = TRUE)
}