Is there a JSON equivalent of XQuery/XPath?

Is there a JSON equivalent of XQuery/XPath?

When searching for items in complex JSON arrays and hashes, like:
{ “id”: 1, “name”: “One”, “objects”: [
{ “id”: 1, “name”: “Response 1”, “objects”: [
// etc.

Is there some kind of query language I can used to find an item in [0].objects where id = 3?


Solution 1:

Yup, it’s called JSONPath. The source is now on GitHub.

It’s also integrated into DOJO.

Solution 2:

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.

Solution 3:

Other alternatives I am aware of are

  1. JSONiq specification, which specifies two subtypes of languages: one that hides XML details and provides JS-like syntax, and one that enriches XQuery syntax with JSON constructors and such. Zorba implements JSONiq.
  2. Corona, which builds on top of MarkLogic provides a REST interface for storing, managing, and searching XML, JSON, Text and Binary content.
  3. MarkLogic 6 and later provide a similar REST interface as Corona out of the box.
  4. MarkLogic 8 and later support JSON natively in both their XQuery and Server-side JavaScript environment. You can apply XPath on it.
Related:  ES6 Iterate over class methods


Solution 4:

To summarise some of the current options for traversing/filtering JSON data, and provide some syntax examples…

  • JSPath

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

  • json:select() (inspired more by CSS selectors)

    .automobiles .maker:val("Honda") .model

  • JSONPath (inspired more by XPath)


I think JSPath looks the nicest, so I’m going to try and integrate it with my AngularJS + CakePHP app.

(I originally posted this answer in another thread but thought it would be useful here, also.)

Solution 5:

Try to using JSPath

JSPath is a domain-specific language (DSL) that enables you to navigate and find data within your JSON documents. Using JSPath, you can select items of JSON in order to retrieve the data they contain.

JSPath for JSON like an XPath for XML.

It is heavily optimized both for Node.js and modern browsers.

Solution 6:

XQuery can be used to query JSON, provided that the processor offers JSON support. This is a straightforward example how BaseX can be used to find objects with “id” = 1:

    { "id": 1, "name": "One", "objects": [
        { "id": 1, "name": "Response 1", "objects": [ "etc." ] }
]')//value[.//id = 1]