Learn R Programming

RJSONIO (version 0.5-0)

toJSON: Convert an R object to a string in Javascript Object Notation

Description

This function and its methods convert an R object into a string that represents the object in Javascript Object Notation (JSON).

The different methods try to map R's vectors to JSON arrays and associative arrays. There is ambiguity here as an R vector of length 1 can be a JSON scalar or an array with one element. When there are names on the R vector, the descision is clearer. We have introduced the emptyNamedList variable to identify an empty list that has an empty names character vector and so maps to an associative array in JSON, albeit an empty one.

Objects of class AsIs in R, i.e. that are enclosed in a call to I() are treated as containers even if they are of length 1. This allows callers to indicate the desired representation of an R "scalar" as an array of length 1 in JSON

Usage

toJSON(x, container = length(x) > 1 || length(names(x)) > 0, collapse = "", ...)x{the R object to be converted to JSON format}
  ...{additional arguments controlling the formatting of the
    JSON. 
  }
  container{a logical value indicating whether to treat the
    object as a vector/container or a scalar and so represent it as an
    array or primitive in JavaScript.}
  collapse{a string that is used as the separator when combining the individual lines of the 
    generated JSON content}

A string containing the JSON content. http://www.json.org [object Object]

fromJSON toJSON(1:10) toJSON(rnorm(3)) toJSON(rnorm(3), digits = 4)

toJSON(c("Duncan", "Temple Lang"))

toJSON(c(FALSE, FALSE, TRUE))

# List of elements toJSON(list(1L, c("a", "b"), c(FALSE, FALSE, TRUE), rnorm(3))) # with digits controlling formatting of sub-elements toJSON(list(1L, c("a", "b"), c(FALSE, FALSE, TRUE), rnorm(3)), digits = 10)

# nested lists toJSON(list(1L, c("a", "b"), list(c(FALSE, FALSE, TRUE), rnorm(3))))

# with names toJSON(list(a = 1L, c("a", "b"), c(FALSE, FALSE, TRUE), rnorm(3)))

setClass("TEMP", representation(a = "integer", xyz = "logical")) setClass("TEMP1", representation(one = "integer", two = "TEMP"))

new("TEMP1", one = 1:10, two = new("TEMP", a = 4L, xyz = c(TRUE, FALSE)))

toJSON(list()) toJSON(emptyNamedList) toJSON(I(list("hi"))) toJSON(I("hi"))

x = list(list(), emptyNamedList, I(list("hi")), "hi", I("hi")) toJSON(x)

IO programming

Arguments