File: prettify.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 (33 lines) | stat: -rw-r--r-- 922 bytes parent folder | download | duplicates (6)
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
#' Prettify adds indentation to a JSON string; minify removes all indentation/whitespace.
#'
#' @rdname prettify
#' @title Prettify or minify a JSON string
#' @name prettify, minify
#' @aliases minify prettify
#' @export prettify minify
#' @param txt JSON string
#' @param indent number of spaces to indent
#' @useDynLib jsonlite R_reformat
#' @examples myjson <- toJSON(cars)
#' cat(myjson)
#' prettify(myjson)
#' minify(myjson)
prettify <- function(txt, indent = 4) {
  txt <- paste(txt, collapse = "\n")
  reformat(txt, TRUE, indent_string = paste(rep(" ", as.integer(indent)), collapse=""))
}

#' @rdname prettify
minify <- function(txt) {
  txt <- paste(txt, collapse = "\n")
  reformat(txt, FALSE)
}

reformat <- function(x, pretty, indent_string = ""){
  out <- .Call(R_reformat, x, pretty, indent_string = indent_string);
  if(out[[1]] == 0) {
    return(out[[2]])
  } else {
    stop(out[[2]], call.=FALSE)
  }
}