-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson-aaquickstart.rmd
More file actions
55 lines (41 loc) · 2.43 KB
/
json-aaquickstart.rmd
File metadata and controls
55 lines (41 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
---
Title: "Getting started with JSON and jsonlite"
date: "`r Sys.Date()`"
output:
rmarkdown::html_document
vignette: >
%\VignetteIndexEntry{Getting started with JSON and jsonlite}
%\VignetteEngine{knitr::rmarkdown}
\usepackage[utf8]{inputenc}
---
```{r include=FALSE}
tutorial::go_interactive()
```
```{r echo=FALSE}
library(knitr)
opts_chunk$set(comment="")
```
# Getting started with JSON and jsonlite
The jsonlite package is a JSON parser/generator optimized for the web. Its main strength is that it implements a bidirectional mapping between JSON data and the most important R data types. Thereby we can convert between R objects and JSON without loss of type or information, and without the need for any manual data munging. This is ideal for interacting with web APIs, or to build pipelines where data structures seamlessly flow in and out of R using JSON.
```{r message=FALSE}
library(jsonlite)
all.equal(mtcars, fromJSON(toJSON(mtcars)))
```
This vignette introduces basic concepts to get started with jsonlite. For a more detailed outline and motivation of the mapping, see: [arXiv:1403.2805](http://arxiv.org/abs/1403.2805).
## Simplification
Simplification is the process where JSON arrays automatically get converted from a list into a more specific R class. The `fromJSON` function has 3 arguments which control the simplification process: `simplifyVector`, `simplifyDataFrame` and `simplifyMatrix`. Each one is enabled by default.
| JSON structure | Example JSON data | Simplifies to R class | Argument in fromJSON |
| ----------------------|----------------------------------------------------------|-----------------------|----------------------|
| Array of primitives | `["Amsterdam", "Rotterdam", "Utrecht", "Den Haag"]` | Atomic Vector | simplifyVector |
| Array of objects | `[{"name":"Erik", "age":43}, {"name":"Anna", "age":32}]` | Data Frame | simplifyDataFrame |
| Array of arrays | `[ [1, 2, 3], [4, 5, 6] ]` | Matrix | simplifyMatrix |
### Atomic Vectors
When `simplifyVector` is enabled, JSON arrays containing **primitives** (strings, numbers, booleans or null) simplify into an atomic vector:
```{r}
# A JSON array of primitives
json <- '["Mario", "Peach", null, "Bowser"]'
# Simplifies into an atomic vector
fromJSON(json)
# No simplification:
fromJSON(json, simplifyVector = FALSE)
```