---
title: "Parsing JSON"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Parsing JSON}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

```{r setup}
library(RJSONIO)
```

`fromJSON()` parses JSON arrays, objects, strings, numbers, booleans, and nulls.
The return type depends on the JSON shape and the simplification settings.

## Parse JSON text

```{r parse-text}
fromJSON("[1, 3, 10, 19]")

fromJSON('{"a": 1, "b": true, "c": "value"}')
```

Use `I()` when passing JSON text that should be treated explicitly as content.

```{r parse-as-is}
fromJSON(I("[3.1415]"))
```

## Parse files

File paths are read from disk when `asText = FALSE`, which is the default for
plain character strings that do not look like JSON content.

```{r parse-file}
path <- system.file("sampleData", "keys.json", package = "RJSONIO")
parsed <- fromJSON(path)

names(parsed)
names(parsed$menu)
```

## Parse connections

Connections are useful when JSON content is already available through an R
connection object.

```{r parse-connection}
con <- textConnection(c("[[1, 2, 3, 4],", "[5, 6, 7, 8]]"))
parsed <- fromJSON(con)
close(con)

parsed
```

## Null values

By default, JSON `null` maps to `NULL` in list output. Use `nullValue` to
preserve positions in simplified vectors.

```{r parse-null}
fromJSON("[1, null, 4]", simplify = FALSE)
fromJSON("[1, null, 4]", simplify = TRUE, nullValue = -999)
```

## Simplification

`Strict` simplification keeps incompatible values as lists. Less strict
simplification can coerce mixed compatible values into an atomic vector.

```{r parse-simplify}
fromJSON('[1, "2.3", "abc"]', simplify = Strict)
fromJSON('[1, "2.3", "abc"]', simplify = TRUE)
fromJSON('{"a": 1, "b": 2}', simplify = Strict)
fromJSON('{"a": 1, "b": 2}', simplify = FALSE)
```

## Sample data

The package includes JSON fixtures that are useful for examples and local
checks.

```{r sample-data}
sample_dir <- system.file("sampleData", package = "RJSONIO")
head(list.files(sample_dir, pattern = "[.]json$"))

widget <- fromJSON(file.path(sample_dir, "widget.json"))
names(widget)
```
