Internet-Draft | JSONPath | July 2020 |
Gössner & Bormann | Expires 13 January 2021 | [Page] |
insert abstract here¶
This document picks up the popular JSONPath specification dated 2007-02-21 and provides a more normative definition for it. It is intended as a submission to the IETF DISPATCH WG, in order to find the right way to complete standardization of this specification. In its current state, it is a strawman document showing what needs to be covered.¶
Comments and issues can be directed at the github repository insert repo here as well as (for the time when the more permanent home is being decided) at the dispatch@ietf.org mailing list.¶
This Internet-Draft is submitted in full conformance with the provisions of BCP 78 and BCP 79.¶
Internet-Drafts are working documents of the Internet Engineering Task Force (IETF). Note that other groups may also distribute working documents as Internet-Drafts. The list of current Internet-Drafts is at https://datatracker.ietf.org/drafts/current/.¶
Internet-Drafts are draft documents valid for a maximum of six months and may be updated, replaced, or obsoleted by other documents at any time. It is inappropriate to use Internet-Drafts as reference material or to cite them other than as "work in progress."¶
This Internet-Draft will expire on 13 January 2021.¶
Copyright (c) 2020 IETF Trust and the persons identified as the document authors. All rights reserved.¶
This document is subject to BCP 78 and the IETF Trust's Legal Provisions Relating to IETF Documents (https://trustee.ietf.org/license-info) in effect on the date of publication of this document. Please review these documents carefully, as they describe your rights and restrictions with respect to this document. Code Components extracted from this document must include Simplified BSD License text as described in Section 4.e of the Trust Legal Provisions and are provided without warranty as described in the Simplified BSD License.¶
This document picks up the popular JSONPath specification dated 2007-02-21 [JSONPath-orig] and provides a more normative definition for it. It is intended as a submission to the IETF DISPATCH WG, in order to find the right way to complete standardization of this specification. In its current state, it is a strawman document showing what needs to be covered.¶
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in BCP 14 [RFC2119] [RFC8174] when, and only when, they appear in all capitals, as shown here.¶
The grammatical rules in this document are to be interpreted as described in [RFC5234].¶
The terminology of [RFC8259] applies.¶
A frequently emphasized advantage of XML is the availability of plenty tools to analyse, transform and selectively extract data out of XML documents. [XPath] is one of these powerful tools.¶
In 2007, the need for something solving the same class of problems for the emerging JSON community became apparent, specifically for:¶
So how does such a tool look like when done for JSON? When defining a JSONPath, how should expressions look like?¶
The XPath expression¶
/store/book[1]/title¶
looks like¶
x.store.book[0].title¶
or¶
x['store']['book'][0]['title']¶
in popular programming languages such as JavaScript, Python and PHP, with a variable x holding the JSON data item. Here we observe that such languages already have a fundamentally XPath-like feature built in.¶
The JSONPath tool in question should:¶
JSONPath expressions always apply to a JSON data item in the same way
as XPath expressions are used in combination with an XML document.
Since a JSON data item is usually anonymous and doesn't necessarily
have a "root member object", JSONPath used the abstract name $
to
refer to the top level object of the data item.¶
JSONPath expressions can use the dot-notation¶
$.store.book[0].title¶
or the bracket-notation¶
$['store']['book'][0]['title']¶
for paths input to a JSONPath processor. Where a JSONPath processor uses JSONPath expressions for internal purposes or as output paths, these will always be converted to the more general bracket-notation.¶
JSONPath allows the wildcard symbol *
for member names and array
indices. It borrows the descendant operator ..
from [E4X] and
the array slice syntax proposal [start:end:step]
[SLICE] from ECMASCRIPT 4.¶
JSONPath can employ an underlying scripting language, expressions of
which, written in parentheses: (<expr>)
, can be used as an
alternative to explicit names or indices as in:¶
$.store.book[(@.length-1)].title¶
The symbol @
is used for the current object.
Filter expressions are supported via the syntax ?(<boolean expr>)
as in¶
$.store.book[?(@.price < 10)].title¶
Here is a complete overview and a side by side comparison of the JSONPath syntax elements with its XPath counterparts.¶
XPath | JSONPath | Description |
---|---|---|
/
|
$
|
the root object/element |
.
|
@
|
the current object/element |
/
|
. or []
|
child operator |
..
|
n/a | parent operator |
//
|
..
|
nested descendants. JSONPath borrows this syntax from E4X. |
*
|
*
|
wildcard. All objects/elements regardless of their names. |
@
|
n/a | attribute access. JSON data items don't have attributes. |
[]
|
[]
|
subscript operator. XPath uses it to iterate over element collections and for predicates. In JavaScript and JSON it is the native array operator. |
|
|
[,]
|
Union operator in XPath results in a combination of node sets. JSONPath allows alternate names or array indices as a set. |
n/a |
[start:end:step]
|
array slice operator borrowed from ES4. |
[]
|
?()
|
applies a filter (script) expression. |
n/a |
()
|
script expression, using the underlying script engine. |
()
|
n/a | grouping in Xpath |
XPath has a lot more to offer (location paths in unabbreviated syntax, operators and functions) than listed here. Moreover there is a significant difference how the subscript operator works in Xpath and JSONPath:¶
This section provides some more examples for JSONPath expressions. The examples are based on a simple JSON data item patterned after a typical XML example representing a bookstore (that also has bicycles):¶
The examples in Table 2 presume an underlying script language that allows obtaining the number of items in an array, testing for the presence of a map member, and performing numeric comparisons of map member values with a constant.¶
XPath | JSONPath | Result |
---|---|---|
/store/book/author
|
$.store.book[*].author
|
the authors of all books in the store |
//author
|
$..author
|
all authors |
/store/*
|
$.store.*
|
all things in store, which are some books and a red bicycle. |
/store//price
|
$.store..price
|
the price of everything in the store. |
//book[3]
|
$..book[2]
|
the third book |
//book[last()]
|
$..book[(@.length-1)] $..book[-1:]
|
the last book in order. |
//book[position()<3]
|
$..book[0,1] $..book[:2]
|
the first two books |
//book[isbn]
|
$..book[?(@.isbn)]
|
filter all books with isbn number |
//book[price<10]
|
$..book[?(@.price<10)]
|
filter all books cheapier than 10 |
//*
|
$..*
|
all Elements in XML document. All members of JSON data item. |
[TBD: This section needs to be fleshed out in detail. The text given here is intended to give the flavor of that detail, not to be the actual definition that is to be defined.]¶
JSONPath expressions, "queries" for short in this specification, are character strings, represented in UTF-8 unless otherwise required by the context in which they are used.¶
When applied to a JSON data item, a query returns a (possibly empty) list of "positions" in the data item that match the JSONPath expression.¶
Within a script, @ stands for the position under consideration. [TBD: define underlying scripting language, if there is to be a standard one]¶
[TBD: define handling of spaces]¶
A JSONPath starts at the root of the argument; the "current list" of positions is initialized to that root. Each step applies the semantics of that step to each of the positions in the "current list", returning another list; the "current list" is replaced by the concatenation of all these returned lists, and the next step begins. When all steps have been performed, the "current list" is returned, depending on the choices of the context either as a list of data items or as a list of output paths. [TBD: define the order of that list]¶
[TBD: Define all the steps]¶
[TBD: Define details of Output Path]¶
$
and local @
symbols are expanded by a simple regular expression.¶
TBD: Define a media type for JSON Path expressions.¶
This appendix has been copied from the similar section in [JSONPath-orig], with few changes. It is informative, intended to supply more examples and give an impression for what could be a typical JSONPath API.¶
JSONPath is implemented in JavaScript for client-side usage and ported over to PHP for use on the server.¶
All you need to do is downloading either of the files¶
jsonpath.js
[JSONPath-impl]¶
jsonpath.php
[JSONPath-impl]¶
include it in your program and use the simple API consisting of one single function.¶
jsonPath(obj, expr [, args])¶
false
in case of no match.¶
var o = { /*...*/ }, // the 'store' JSON object from above res1 = jsonPath(o, "$..author").toJSONString(), res2 = jsonPath(o, "$..author", {resultType:"PATH"}).toJSONString();¶
We need here to convert the JSON string to a PHP array first. I am using Michal Migurski's JSON parser [JSON-PHP] for that.¶
require_once('json.php'); // JSON parser require_once('jsonpath.php'); // JSONPath evaluator $json = '{ ... }'; // JSON data item from above $parser = new Services_JSON(SERVICES_JSON_LOOSE_TYPE); $o = $parser->decode($json); $match1 = jsonPath($o, "$..author"); $match2 = jsonPath($o, "$..author", array("resultType" => "PATH")); $res1 = $parser->encode($match1); $res2 = $parser->encode($match2);¶
Both JavaScript and PHP example result in the following JSON arrays (as strings):¶
res1: [ "Nigel Rees", "Evelyn Waugh", "Herman Melville", "J. R. R. Tolkien" ] res2: [ "$['store']['book'][0]['author']", "$['store']['book'][1]['author']", "$['store']['book'][2]['author']", "$['store']['book'][3]['author']" ]¶
Please note that the return value of jsonPath is an array, which is also a valid JSON data item. So you might want to apply jsonPath to the resulting data item again or use one of your favorite array methods as sort with it.¶
This specification is based on Stefan Gössner's original online article defining JSONPath [JSONPath-orig].¶
The books example was taken from http://coli.lili.uni-bielefeld.de/~andreas/Seminare/sommer02/books.xml -- a dead link now.¶