Is there a JSON equivalent of XQuery/XPath?

Solution 1:

Yup, it's called JSONPath:

It's also integrated into DOJO.

Solution 2:

JMESPath is quite a mature library with a detailed specification and support for multiple languages.

Syntax Examples:
// Select a single item
people[1].firstName

// Select a slice of an array
people[0:5]

// Select all the first names
people[*].firstName

// Select all first names based on search term
people[?state=='VA'].firstName

// Count how many people are over 35
length(people[?age>`35`])

// Select only the name and age of people over 35
people[?age>`35`].{name: name, age: age}

// Join expressions together to sort and join elements into a string
people[?state == 'WA'].name | sort(@) | join(', ', @)

There are plenty more live examples you can play with in the docs.

The JS library is 19kb minified, so possibly larger than some, but considering the extensive features, you might find it worth it.

Other Options

There are also some other options for traversing/filtering JSON data, along with some syntax examples to help you compare...

  • JSPath
    .automobiles{.maker === "Honda" && .year > 2009}.model

  • json:select() (inspired more by CSS selectors)
    .automobiles .maker:val("Honda") .model

  • JSONPath (inspired more by XPath)
    $.automobiles[?(@.maker='Honda')].model

Solution 3:

I think JSONQuery is a superset of JSONPath and thus replaces it in dojo. Then there's also RQL.

From Dojo documentation:

JSONQuery is an extended version of JSONPath with additional features for security, ease of use, and a comprehensive set of data querying tools including filtering, recursive search, sorting, mapping, range selection, and flexible expressions with wildcard string comparisons and various operators.

JSONselect has another point of view on the question (CSS selector-like, rather than XPath) and has a JavaScript implementation.