fromJSON(I(toJSON(1:10)))
fromJSON(I(toJSON(1:10 + .5)))
fromJSON(I(toJSON(c(TRUE, FALSE, FALSE, TRUE))))
x = fromJSON('{"ok":true,"id":"x123","rev":"1-1794908527"}')
# Reading from a connection. It is a text connection so we could
# just read the text directly, but this could be a dynamic connection.
m = matrix(1:27, 9, 3)
txt = toJSON(m)
con = textConnection(txt)
identical(m, fromJSON(con))
# Use a connection and move the cursor ahead to skip over some lines.
f = system.file("sampleData", "obj1.json", package = "RJSONIO")
con = file(f, "r")
readLines(con, 1)
fromJSON(con)
close(con)
f = system.file("sampleData", "embedded.json", package = "RJSONIO")
con = file(f, "r")
readLines(con, 1) # eat the first line
fromJSON(con, maxNumLines = 4)
close(con)
if(require(rjson)) {
# We see an approximately a factor of 3.9 speed up when we use
# this approach that mixes C-level tokenization and an R callback
# function to gather the results into objects.
f = system.file("sampleData", "usaPolygons.as", package = "RJSONIO")
t1 = system.time(a <- RJSONIO:::fromJSON(f))
t2 = system.time(b <- fromJSON(paste(readLines(f), collapse = "\n")))
}
# Use a C routine
fromJSON(I("[1, 2, 3, 4]"),
getNativeSymbolInfo("R_json_testNativeCallback", "RJSONIO"))
# Use a C routine that populates an R integer vector with the
# elements read from the JSON array. Note that we must ensure
# that the array is big enough.
fromJSON(I("[1, 2, 3, 4]"),
getNativeSymbolInfo("R_json_IntegerArrayCallback", PACKAGE = "RJSONIO"),
data = rep(1L, 5))
x = fromJSON(I("[1.1, 2.2, 3.3, 4.4]"),
getNativeSymbolInfo("R_json_RealArrayCallback", PACKAGE = "RJSONIO"),
data = rep(1, 5))
length(x) = 4
# This illustrates a "specialized" handler which knows what it is
# expecting and pre-allocates the answer
# This then populates the answer with the values.
# The speed improvement is 1.8 versus "infinity"!
x = rnorm(1000000)
str = toJSON(x, digits = 6)
fromJSON(I(str),
getNativeSymbolInfo("R_json_RealArrayCallback", PACKAGE = "RJSONIO"),
data = numeric(length(x)))
# This is another example of very fast reading of specific JSON.
x = matrix(rnorm(1000000), 1000, 1000)
str = toJSON(x, digits = 6)
v = fromJSON(I(str),
getNativeSymbolInfo("R_json_RealArrayCallback", PACKAGE = "RJSONIO"),
data = matrix(0, 1000, 1000))
Run the code above in your browser using DataLab