JSONPath - XPath for JSON (goessner.net)

3 points by flaviojuvenal ↗ HN
There are also implementations in many languages as Java (https://github.com/jayway/JsonPath), Python (http://pypi.python.org/pypi/jsonpath/), Ruby (https://github.com/joshbuddy/jsonpath) and Perl (https://github.com/masukomi/jsonpath-perl).

6 comments

[ 4.1 ms ] story [ 27.1 ms ] thread
Legitimate question: can someone tell me why something like this would be useful? Don't most libraries that handle json decoding make parsing it extremely easy? I read through the examples on the site, and I'm still not convinced something like JSONPath is necessary for what they're doing.
The project that I am working is document-oriented, meaning that the schema cannot be well controlled. We end up with a lot of code is very guarded code that looks something like this:

  if(((json.author || {}).lastPublish || {}).publishDate)) {
    do something
  }
It can be replaced with:

  if(jsonPath(json, "$.author.lastPublish .publishDate")) {
    do something
  }
Or better, get all book publish dates, regardless of number of books, if any even exist, and those that might have a missing publishDate:

  publishDates = jsonPath(json,"$.author.books[*].publishDate");
Parsing and accessing are two different tasks. Even if you have an entire JSON (or XML) data structure in memory, getting to the right pieces can be difficult. “Return all of the order entries contained in an a shipment of type ‘Billable‘ whose total price is less than $500.” In the JSON world you’d typically write some imperative code to loop through the data. XPath allows you describe things like this without having to get into the nitty gritty of how the traversal is actually performed, similar to how CSS selectors work with the browser DOM.

I do look forward to the JSON community (re?)developing schema and transformation languages to go along with this.

I made a similiar type of library for Erlang called props[1], which also includes common data manipulation tasks like merging, replacing data at a path, etc.

[1] https://github.com/greyarea/props

I wrote a really simple JSON parsing tool using a JavaScript implementation of JSONPath. It's been invaluable as a tool to analyze the JSON returned by my APIs.

I guess I should add a nice template (right now it's really crude HTML with just the bare necessities) and release it to the world... maybe next weekend :)