knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.path = "README-" )
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()"} ] } }}
json <- '{"menu": { "id": "file", "value": "File", "popup": { "menuitem": [ {"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"} ] } }}' json <- RJSONIO::fromJSON(json) library(rjsonpath)
Via read_json
this can be read into R as:
json
Pretty horrible right? To gather all the onclick
methods
into a vector with base R you might write:
sapply(json$menu$popup$menuitem, `[[`, "onclick")
Using rjsonpath
this could instead be:
json_path(json, "$.menu.popup.menuitem[*].onclick")
Or even just:
json_path(json, "$..onclick")
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.