knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.path = "README-"
)

rjsonpath

travis_status codecov docs_badge CRAN_badge

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

Install from github with:

devtools::install_github("blmoore/rjsonpath")

Usage

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.

Advanced expressions



blmoore/rjsonpath documentation built on May 21, 2019, 2:21 p.m.