Learn R Programming

jsontools (version 0.1.0)

format_json: Convert R objects to JSON

Description

format_json is only a wrapper around the great jsonlite::toJSON(). The differences are

  • expose argument json_verbatim, rownames, and always_decimal.

  • use json_verbatim = TRUE by default so that JSON isn't escaped again.

  • return a json2 object.

format_json_list() converts each element of a list to JSON.

To make sure that a length one vector is not turned into an array use json_u() or jsonlite::unbox().

Usage

format_json(
  x,
  null = c("list", "null"),
  na = c("null", "string"),
  auto_unbox = FALSE,
  dataframe = c("rows", "columns", "values"),
  matrix = c("rowmajor", "columnmajor"),
  Date = c("ISO8601", "epoch"),
  POSIXt = c("string", "ISO8601", "epoch", "mongo"),
  factor = c("string", "integer"),
  complex = c("string", "list"),
  raw = c("base64", "hex", "mongo", "int", "js"),
  digits = 4,
  json_verbatim = TRUE,
  force = FALSE,
  pretty = FALSE,
  rownames = FALSE,
  always_decimal = FALSE,
  ...
)

format_json_list( x, null = c("list", "null"), na = c("null", "string"), auto_unbox = FALSE, dataframe = c("rows", "columns", "values"), matrix = c("rowmajor", "columnmajor"), Date = c("ISO8601", "epoch"), POSIXt = c("string", "ISO8601", "epoch", "mongo"), factor = c("string", "integer"), complex = c("string", "list"), raw = c("base64", "hex", "mongo", "int", "js"), digits = 4, json_verbatim = TRUE, force = FALSE, pretty = FALSE, rownames = FALSE, always_decimal = FALSE, ... )

Arguments

x

the object to be encoded

null, na, auto_unbox, dataframe, matrix, Date

passed on to jsonlite::toJSON.

POSIXt, factor, complex, raw, digits, force, pretty, ...

passed on to jsonlite::toJSON.

json_verbatim

Leave JSON as it is and do not encode it again?

rownames

For data.frames add a field _row with the row name?

always_decimal

Use real number notation in whole number doubles?

Value

A json2 vector.

See Also

write_json(), format_json_rowwise()

Examples

Run this code
# NOT RUN {
# null
x_null <- list(a = NULL, b = 1)
format_json(x_null)
format_json(x_null, null = "null")

# na
x_na <- list(a = NA, b = 1)
format_json(x_na)
format_json(x_na, na = "string")

# auto_unbox
x_autounbox <- list(1, 1:3)
format_json(x_autounbox)
format_json(x_autounbox, auto_unbox = TRUE)

# dataframe conversion
x_df <- iris[1:2, ]
format_json(x_df, pretty = TRUE)
format_json(x_df, dataframe = "columns", pretty = TRUE)
format_json(x_df, dataframe = "values", pretty = TRUE)

# json_verbatim
x_json <- json2('["a","b"]')
format_json(x_json)
format_json(x_json, json_verbatim = FALSE)

# Decimal vs significant digits
x <- 10 + pi
format_json(x)
format_json(x, digits = NA)
format_json(x, digits = 2)
format_json(x, digits = I(2))

# Force decimal representation
format_json(12)
format_json(12, always_decimal = TRUE)
# }

Run the code above in your browser using DataLab