Reading JSON into R usually leaves you with some deeply-nested list objects which are a pain to munge and navigate — applying path expressions is one way to make this easier. rjsonpath
implements JSONPath, a selector / querying language for JSON, similar to XPath for XML.
Install from github with:
devtools::install_github("blmoore/rjsonpath")
As an example, take this simple JSON:
{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}
Via read_json
this can be read into R as:
json
#> $menu
#> $menu$id
#> [1] "file"
#>
#> $menu$value
#> [1] "File"
#>
#> $menu$popup
#> $menu$popup$menuitem
#> $menu$popup$menuitem[[1]]
#> value onclick
#> "New" "CreateNewDoc()"
#>
#> $menu$popup$menuitem[[2]]
#> value onclick
#> "Open" "OpenDoc()"
#>
#> $menu$popup$menuitem[[3]]
#> value onclick
#> "Close" "CloseDoc()"
Pretty horrible right? To gather all the onclick
methods into a vector with base R you might write:
sapply(json$menu$popup$menuitem, `[[`, "onclick")
#> [1] "CreateNewDoc()" "OpenDoc()" "CloseDoc()"
Using rjsonpath
this could instead be:
json_path(json, "$.menu.popup.menuitem[*].onclick")
#> [1] "CreateNewDoc()" "OpenDoc()" "CloseDoc()"
Or even just:
json_path(json, "$..onclick")
#> [1] "CreateNewDoc()" "OpenDoc()" "CloseDoc()"
For more more complex examples, see below.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.