## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")

## ----setup--------------------------------------------------------------------
library(zujson)

## -----------------------------------------------------------------------------
body <- '{
  "total": 2,
  "cursor": null,
  "items": [
    {"id": 1, "name": "Ada", "tags": ["admin", "dev"], "score": 9.5},
    {"id": 2, "name": "Grace", "tags": [], "score": null}
  ]
}'

## -----------------------------------------------------------------------------
res <- json_parse(body)
str(res)

## -----------------------------------------------------------------------------
str(json_parse('[1, "Ada"]'))

## -----------------------------------------------------------------------------
json_parse(body, data_frame = TRUE)$items

## -----------------------------------------------------------------------------
new_item <- list(name = "Edsger", tags = "dev", active = TRUE)
cat(json_write(new_item))

## -----------------------------------------------------------------------------
new_item$tags <- I("dev")
cat(json_write(new_item))

## -----------------------------------------------------------------------------
identical(json_parse(json_write(res)), res)

## -----------------------------------------------------------------------------
bytes <- json_write_raw(new_item)
head(bytes)

str(json_parse(bytes))

## -----------------------------------------------------------------------------
path <- tempfile(fileext = ".json")
writeBin(bytes, path)

json_parse_file(path)$name

## -----------------------------------------------------------------------------
truncated <- substr(body, 1, 40)
json_validate(truncated)

## ----error = TRUE-------------------------------------------------------------
try({
json_parse(truncated)
})

## -----------------------------------------------------------------------------
tryCatch(
  json_parse(truncated),
  zujson_error = function(e) class(e)[1]
)

## -----------------------------------------------------------------------------
lines <- json_write_ndjson(res$items)
cat(lines)

## -----------------------------------------------------------------------------
records <- json_parse_ndjson(lines)
identical(records, res$items)

