]> JSONPath: Query expressions for JSON Fachhochschule Dortmund
Sonnenstraße 96 Dortmund D-44139 Germany stefan.goessner@fh-dortmund.de
Winchester UK glyn.normington@gmail.com
Universität Bremen TZI
Postfach 330440 Bremen D-28359 Germany +49-421-218-63921 cabo@tzi.org
ART JSONPath WG JSON JSONPath defines a string syntax for selecting and extracting values within a JSON (RFC 8259) value. Status information for this document may be found at . Discussion of this document takes place on the JSON Path Working Group mailing list (), which is archived at . Subscribe at . Source for this draft and an issue tracker can be found at .
Introduction JSON is a popular representation format for structured data values. JSONPath defines a string syntax for identifying values within a JSON value. JSONPath is not intended as a replacement for, but as a more powerful companion to, JSON Pointer . See .
Terminology 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 when, and only when, they appear in all capitals, as shown here. The grammatical rules in this document are to be interpreted as ABNF, as described in . ABNF terminal values in this document define Unicode code points rather than their UTF-8 encoding. For example, the Unicode PLACE OF INTEREST SIGN (U+2318) would be defined in ABNF as %x2318. The terminology of applies except where clarified below. The terms "Primitive" and "Structured" are used to group the types as in . Definitions for "Object", "Array", "Number", and "String" remain unchanged. Importantly "object" and "array" in particular do not take on a generic meaning, such as they would in a general programming context. Additional terms used in this specification are defined below.
Value:
As per , a structure complying to the generic data model of JSON, i.e., composed of components such as structured values, namely JSON objects and arrays, and primitive data, namely numbers and text strings as well as the special values null, true, and false.
Type:
As per , one of the six JSON types (strings, numbers, booleans, null, objects, arrays).
Member:
A name/value pair in an object. (Not itself a value.)
Name:
The name in a name/value pair constituting a member. (Also known as "key", "tag", or "label".) This is also used in , but that specification does not formally define it. It is included here for completeness.
Element:
A value in an array. (Not to be confused with XML element.)
Index:
A non-negative integer that identifies a specific element in an array. Note that the term indexing is also used for accessing elements using negative integers (), and for accessing member values in an object using their member name.
Query:
Short name for JSONPath expression.
Argument:
Short name for the value a JSONPath expression is applied to.
Node:
The pair of a value along with its location within the argument.
Root Node:
The unique node whose value is the entire argument.
Children (of a node):
If the node is an array, each of its elements, or if the node is an object, each of its member values (but not its member names). If the node is neither an array nor an object, it has no children.
Descendants (of a node):
The children of the node, together with the children of its children, and so forth recursively. More formally, the descendants relation between nodes is the transitive closure of the children relation.
Nodelist:
A list of nodes. The output of applying a query to an argument is manifested as a list of nodes. While this list can be represented in JSON, e.g. as an array, the nodelist is an abstract concept unrelated to JSON values.
Normalized Path:
A simple form of JSONPath expression that identifies a node by providing a query that results in exactly that node. Similar to, but syntactically different from, a JSON Pointer .
Unicode Scalar Value:
Any Unicode code point except high-surrogate and low-surrogate code points. In other words, integers in either of the inclusive base 16 ranges 0 to D7FF and E000 to 10FFFF. JSON values of type string are sequences of Unicode scalar values.
Singular Path:
A JSONPath expression built from selectors which each select at most one node.
//PICKER//:
A single item within a bracketed ([]) child selector that matches the values which are to be selected.
For the purposes of this specification, a value as defined by is also viewed as a tree of nodes. Each node, in turn, holds a value. Further nodes within each value are the elements of arrays and the member values of objects and are themselves values. (The type of the value held by a node may also be referred to as the type of the node.) A query is applied to an argument, and the output is a nodelist.
History This document picks up 's popular JSONPath proposal dated 2007-02-21 and provides a normative definition for it. describes how JSONPath was inspired by XML's XPath . JSONPath was intended as a light-weight companion to JSON implementations on platforms such as PHP and JavaScript, so instead of defining its own expression language like XPath did, JSONPath delegated this to the expression language of the platform. While the languages in which JSONPath is used do have significant commonalities, over time this caused non-portability of JSONPath expressions between the ensuing platform-specific dialects. The present specification intends to remove platform dependencies and serve as a common JSONPath specification that can be used across platforms. Obviously, this means that backwards compatibility could not always be achieved; a design principle of this specification is to go with a "consensus" between implementations even if it is rough, as long as that does not jeopardize the objective of obtaining a usable, stable JSON query language.
Overview of JSONPath Expressions JSONPath expressions are applied to a JSON value, the argument. Within the JSONPath expression, the abstract name $ is used to refer to the root node of the argument, i.e., to the argument as a whole. JSONPath expressions primarily use the bracket notation
but may also use the shorthand dot notation
to build paths that are input to a JSONPath implementation. Generally, the dot notation is preferred for most applications. Mixing these syntaxes within a single path is also useful. JSONPath allows the wildcard symbol * to select any member of an object or any element of an array (). The descendant selector (which starts with ..) recursively selects some or all of the descendants () of a node. The array slice syntax [start:end:step] allows selecting a regular selection of an element from an array, giving a start position, an end position, and possibly a step value that moves the position from the start to the end (). Filter expressions are supported via the syntax ?(<boolean expr>) as in
provides a quick overview of the JSONPath syntax elements. JSONPath Description $ root node selector [*] wildcard selector: selects all immediate descendants of objects and arrays ..[*] descendant wildcard selector: recursive version of the wildcard selector [<//PICKERS//>] child selector selects zero or more children of JSON objects and arrays; contains one or more //PICKERS//, separated by commas ..[<//PICKERS//>] descendant child selector: recursive version of the child selector 'name' name //PICKER//: selects a named child of an object 3 index //PICKER//: selects an indexed child of an array (from 0) 0:100:5 array slice //PICKER//: start:end:step for arrays ?<expr> filter //PICKER//: selects particular children using a boolean expression @ current node selector (valid only within filter //PICKERS//) .name shorthand for ['name'] .* shorthand for [*] ..name shorthand for ..['name'] ..* shorthand for ..[*]
JSONPath Examples This section provides some more examples for JSONPath expressions. The examples are based on the simple JSON value shown in , representing a bookstore (that also has bicycles).
shows some JSONPath queries that might be applied to this example and their intended results. JSONPath Intended result $.store.book[*].author the authors of all books in the store $..author all authors $.store.* all things in store, which are some books and a red bicycle $.store..price the prices of everything in the store $..book[2] the third book $..book[-1] the last book in order $..book[0,1]
$..book[:2]
the first two books $..book[?(@.isbn)] filter all books with ISBN number $..book[?(@.price<10)] filter all books cheaper than 10 $..* all member values and array elements contained in input value
JSONPath Syntax and Semantics
Overview A JSONPath query is a string which selects zero or more nodes of a JSON value. A query MUST be encoded using UTF-8. The grammar for queries given in this document assumes that its UTF-8 form is first decoded into Unicode code points as described in ; implementation approaches that lead to an equivalent result are possible. A string to be used as a JSONPath query needs to be well-formed and valid. A string is a well-formed JSONPath query if it conforms to the ABNF syntax in this document. A well-formed JSONPath query is valid if it also fulfills all semantic requirements posed by this document. To be valid, integer numbers in the JSONPath query that are relevant to the JSONPath processing (e.g., index values and steps) MUST be within the range of exact values defined in I-JSON , namely within the interval [-(253)+1, (253)-1]). To be valid, strings on the right-hand side of the =~ regex matching operator need to conform to . The well-formedness and the validity of JSONPath queries are independent of the JSON value the query is applied to; no further errors relating to the well-formedness and the validity of a JSONPath query can be raised during application of the query to a value. Obviously, an implementation can still fail when executing a JSONPath query, e.g., because of resource depletion, but this is not modeled in the present specification. However, the implementation MUST NOT silently malfunction. Specifically, if a valid JSONPath query is evaluated against a structured value whose size doesn't fit in the range of exact values, interfering with the correct interpretation of the query, the implementation MUST provide an indication of overflow. (Readers familiar with the HTTP error model may be reminded of 400 type errors when pondering well-formedness and validity, while resource depletion and related errors are comparable to 500 type errors.) The JSON value the JSONPath query is applied to is, by definition, a valid JSON value. The parsing of a JSON text into a JSON value and what happens if a JSON text does not represent valid JSON are not defined by this specification. Sections and of identify specific situations that may conform to the grammar for JSON texts but are not interoperable uses of JSON, for instance as they may cause unpredictable behavior. The present specification does not attempt to define predictable behavior for JSONPath queries in these situations. (Note that another warning about interoperability, in , at the time of writing is generally considered to be overtaken by events and causes no issues with the present specification.) Specifically, the "Semantics" subsections of Sections , , , and describe behavior that turns unpredictable when the JSON value for one of the objects under consideration was constructed out of JSON text that exhibits multiple members for a single object that share the same member name ("duplicate names", see ). Also, matching () and comparing ( in Section ) of strings assumes these strings are sequences of Unicode scalar values, turning unpredictable if they aren't ().
Syntax Syntactically, a JSONPath query consists of a root selector ($), which stands for a nodelist that contains the root node of the argument, followed by a possibly empty sequence of selectors.
The syntax and semantics of each selector is defined below.
Semantics In this specification, the semantics of a JSONPath query define the required results and do not prescribe the internal workings of an implementation. The semantics are that a valid query is executed against a value, the argument, and produces a list of zero or more nodes of the value. The query is a sequence of zero or more selectors, each of which is applied to the result of the previous selector and provides input to the next selector. These results and inputs take the form of a nodelist, i.e., a sequence of zero or more nodes. The nodelist presented to the first selector contains a single node, the argument. The nodelist resulting from the last selector is presented as the result of the query; depending on the specific API, it might be presented as an array of the JSON values at the nodes, an array of Normalized Paths referencing the nodes, or both — or some other representation as desired by the implementation. Note that the API must be capable of presenting an empty nodelist as the result of the query. A selector performs its function on each of the nodes in its input nodelist, during such a function execution, such a node is referred to as the "current node". Each of these function executions produces a nodelist, which are then concatenated to produce the result of the selector. A node may be selected more than once and appear that number of times in the nodelist. Duplicate nodes are not removed. The processing within a selector may execute nested queries, which conform to the semantics defined here. Typically, the argument to that query will be the current node of the selector or a set of nodes subordinate to that current node. A syntactically valid selector MUST NOT produce errors. This means that some operations that might be considered erroneous, such as indexing beyond the end of an array, simply result in fewer nodes being selected. Consider this example. With the argument {"a":[{"b":0},{"b":1},{"c":2}]}, the query $.a[*].b selects the following list of nodes: 0, 1 (denoted here by their value). The query consists of $ followed by three selectors: .a, [*], and .b. Firstly, $ selects the root node which is the argument. So the result is a list consisting of just the root node. Next, .a selects from any input node of type object and selects the node of any member value of the input node corresponding to the member name "a". The result is again a list of one node: [{"b":0},{"b":1},{"c":2}]. Next, [*] selects from an input node of type array all its elements (if the input node were of type object, it would select all its member values, but not the member names). The result is a list of three nodes: {"b":0}, {"b":1}, and {"c":2}. Finally, .b selects from any input node of type object with a member name b and selects the node of the member value of the input node corresponding to that name. The result is a list containing 0, 1. This is the concatenation of three lists, two of length one containing 0, 1, respectively, and one of length zero. As a consequence of this approach, if any of the selectors selects no nodes, then the whole query selects no nodes. In what follows, the semantics of each selector are defined for each type of node.
Selectors A JSONPath query consists of a sequence of selectors. Valid selectors are Root selector $ (used at the start of a query and in expressions) Wildcard selector [*] Child selector [<//PICKERS//>], where <//PICKERS//> is one or more of several //PICKER// types, which match the nodes to select, separated by commas Current item selector @ (only valid in filter expressions) The wildcard and value selectors can be made to recursively select values within nested objects and arrays be prefixing them with .. turning them into Descendant wildcard selector ..[*] Descendant child selector ..[<//PICKERS//>]
Root Selector
Syntax Every valid JSONPath query MUST begin with the root selector $.
Semantics The root selector $ selects the root node of the argument and produces a nodelist consisting of that root node.
Examples JSON:
Queries: Query Result Result Path Comment $ {"k": "v"} $ Root node
Wildcard Selector
Syntax The wildcard selector has either the form [*] or the shorthand form .*.
Semantics A wild-selector selects the nodes of all children of an object or array. Applying the wild-selector to a primitive JSON value (that is, a number, a string, true, false, or null) selects no node. The two formats, index-wild-selector and dot-wild-selector, are functionally identical and may be used interchangeably.
Examples JSON:
Queries: Query Result Result Paths Comment $.o[*] 1
2
$['o']['j']
$['o']['k']
Object values $.o[*] 2
1
$['o']['k']
$['o']['j']
Alternative result $.a[*] 5
3
$['a'][0]
$['a'][1]
Array members
Child Selector
Syntax The child selector has the form [<//PICKERS//>] where <//PICKERS//> is a comma-delimited collection of one or more //PICKERS//. Each //PICKER// is defined below.
Semantics A child selector operates on objects and arrays only. It contains a comma-delimited collection of //PICKERS// to indicate which object members and array elements to selects. Each type of //PICKER// functions differently and may be defined to operate on only objects, only arrays, or both. //PICKERS// of different types may be combined within a single child selector. The resulting nodelist of a child selector is the concatenation of the nodelists from each of its //PICKERS// in the order that the //PICKERS// appear in the list. Note that any node matched by more than one //PICKER// is kept as many times in the nodelist.
Name //PICKER//
Syntax A name //PICKER// '<name>' matches at most one object member value. Applying the quoted-member-name to an object value in its input nodelist, its string is required to match the corresponding member value. In contrast to JSON, the JSONPath syntax allows strings to be enclosed in single or double quotes.
A shorthand for quoted-member-name exists as dotted-member-name. These may be used interchangeably. A dotted-member-name starts with a dot . followed by an object's member name.
Member names containing characters other than allowed by dotted-member-name — such as space (U+0020), minus (U+002D), dot (U+002E) or escaped characters which appear in the semantic section below — MUST NOT be used with the dotted-member-name. (Such member names can be addressed by the quoted-member-name syntax instead.) Note: double-quoted strings follow the JSON string syntax (); single-quoted strings follow an analogous pattern ().
Semantics A quoted-member-name string MUST be converted to a member name by removing the surrounding quotes and replacing each escape sequence with its equivalent Unicode character, as in the table below: Escape Sequence Unicode Character Description \b U+0008 BS backspace \t U+0009 HT horizontal tab \n U+000A LF line feed \f U+000C FF form feed \r U+000D CR carriage return \" U+0022 quotation mark \' U+0027 apostrophe \/ U+002F slash (solidus) \\ U+005C backslash (reverse solidus) \uXXXX U+XXXX unicode character A dotted-member-name string is converted to a member name by removing the initial dot. The name //PICKER// applied to an object matches the node of the corresponding member value from it, if and only if that object has a member with that name. Nothing is selected from a value that is not a object. Note that processing the name //PICKER// potentially requires matching strings against strings, with those strings coming from the JSONPath and from member names and string values in the JSON to which it is being applied. Two strings MUST be considered equal if and only if they are identical sequences of Unicode scalar values. In other words, normalization operations MUST NOT be applied to either the string from the JSONPath or from the JSON prior to comparison.
Examples JSON:
Queries: Query Result Result Paths Comment $.o['j j']['k.k'] 3 $['o']['j j']['k.k'] Named value in nested object $.o["j j"]["k.k"] 3 $['o']['j j']['k.k'] Named value in nested object $["'"]["@"] 2 $['\'']['@'] Unusual member names $.j {"k": 3} $['j'] Named value of an object $.j.k 3 $['j']['k'] Named value in nested object
Index //PICKER//
Syntax An index //PICKER// <index> matches at most one array element value.
Applying the numerical element-index is required to select the corresponding element. JSONPath allows it to be negative (see ). Notes: 1. An element-index is an integer (in base 10, as in JSON numbers). 2. As in JSON numbers, the syntax does not allow octal-like integers with leading zeros such as 01 or -01.
Semantics The element-index applied to an array selects an array element using a zero-based index. For example, selector 0 selects the first and selector 4 the fifth element of a sufficiently long array. Nothing is selected, and it is not an error, if the index lies outside the range of the array. Nothing is selected from a value that is not an array. A negative element-index counts from the array end. For example, selector -1 selects the last and selector -2 selects the penultimate element of an array with at least two elements. As with non-negative indexes, it is not an error if such an element does not exist; this simply means that no element is selected.
Examples JSON:
Queries: Query Result Result Paths Comment $.a[1] "b" $['a'][1] Member of array $.a[-2] "a" $['a'][0] Member of array, from the end
Array Slice //PICKER//
Syntax The array slice //PICKER// has the form <start>:<end>:<step>. It matches elements from arrays starting at index <start>, ending at — but not including — <end>, while incrementing by step.
The slice //PICKER// consists of three optional decimal integers separated by colons.
Semantics The slice //PICKER// was inspired by the slice operator of ECMAScript 4 (ES4), which was deprecated in 2014, and that of Python.
Informal Introduction This section is non-normative. Array indexing is a way of selecting a particular element of an array using a 0-based index. For example, the expression 0 selects the first element of a non-empty array. Negative indices index from the end of an array. For example, the expression -2 selects the last but one element of an array with at least two elements. Array slicing is inspired by the behavior of the Array.prototype.slice method of the JavaScript language as defined by the ECMA-262 standard , with the addition of the step parameter, which is inspired by the Python slice expression. The array slice expression start:end:step selects elements at indices starting at start, incrementing by step, and ending with end (which is itself excluded). So, for example, the expression 1:3 (where step defaults to 1) selects elements with indices 1 and 2 (in that order) whereas 1:5:2 selects elements with indices 1 and 3. When step is negative, elements are selected in reverse order. Thus, for example, 5:1:-2 selects elements with indices 5 and 3, in that order and ::-1 selects all the elements of an array in reverse order. When step is 0, no elements are selected. (This is the one case that differs from the behavior of Python, which raises an error in this case.) The following section specifies the behavior fully, without depending on JavaScript or Python behavior.
Detailed Semantics A slice expression selects a subset of the elements of the input array, in the same order as the array or the reverse order, depending on the sign of the step parameter. It selects no nodes from a node that is not an array. A slice is defined by the two slice parameters, start and end, and an iteration delta, step. Each of these parameters is optional. len is the length of the input array. The default value for step is 1. The default values for start and end depend on the sign of step, as follows: Condition start end step >= 0 0 len step < 0 len - 1 -len - 1 Slice expression parameters start and end are not directly usable as slice bounds and must first be normalized. Normalization for this purpose is defined as:
= 0 THEN RETURN i ELSE RETURN len + i END IF ]]>
The result of the array indexing expression i applied to an array of length len is defined to be the result of the array slicing expression i:Normalize(i, len)+1:1. Slice expression parameters start and end are used to derive slice bounds lower and upper. The direction of the iteration, defined by the sign of step, determines which of the parameters is the lower bound and which is the upper bound:
= 0 THEN lower = MIN(MAX(n_start, 0), len) upper = MIN(MAX(n_end, 0), len) ELSE upper = MIN(MAX(n_start, -1), len-1) lower = MIN(MAX(n_end, -1), len-1) END IF RETURN (lower, upper) ]]>
The slice expression selects elements with indices between the lower and upper bounds. In the following pseudocode, the a(i) construct expresses the 0-based indexing operation on the underlying array.
0 THEN i = lower WHILE i < upper: SELECT a(i) i = i + step END WHILE ELSE if step < 0 THEN i = upper WHILE lower < i: SELECT a(i) i = i + step END WHILE END IF ]]>
When step = 0, no elements are selected and the result array is empty. To be valid, the slice expression parameters MUST be in the I-JSON range of exact values, see .
Examples JSON:
Queries: Query Result Result Paths Comment $[1:3] "b"
"c"
$[1]
$[2]
Slice with default step $[1:5:2] "b"
"d"
$[1]
$[3]
Slice with step 2 $[5:1:-2] "f"
"d"
$[5]
$[3]
Slice with negative step $[::-1] "g"
"f"
"e"
"d"
"c"
"b"
"a"
$[6]
$[5]
$[4]
$[3]
$[2]
$[1]
$[0]
Slice in reverse order
Filter //PICKER//
Syntax The filter //PICKER// has the form ?<expr>. It works via iterating over structured values, i.e. arrays and objects.
During the iteration process each array element or object member is visited and its value — accessible via symbol @ — or one of its descendants — uniquely defined by a relative path — is tested against a boolean expression boolean-expr. The current item is selected if and only if the boolean expression yields true.
Paths in filter expressions are Singular Paths, each of which selects at most one node.
Parentheses can be used with boolean-expr for grouping. So filter selection syntax in the original proposal ?(<expr>) is naturally contained in the current lean syntax ?<expr> as a special case.
Comparisons are restricted to Singular Path values and primitive values (that is, numbers, strings, true, false, and null).
" / ; operators "<=" / ">=" ]]>
Alphabetic characters in ABNF are case-insensitive, so "e" can be either "e" or "E". true, false, and null are lower-case only (case-sensitive).
The syntax of regular expressions in the string-literals on the right-hand side of =~ is as defined in .
The following table lists filter expression operators in order of precedence from highest (binds most tightly) to lowest (binds least tightly). Precedence Operator type Syntax 5 Grouping (...) 4 Logical NOT ! 3 Relations == !=
< <= > >=
=~
2 Logical AND && 1 Logical OR ¦¦
Semantics The filter //PICKER// works with arrays and objects exclusively. Its result is a list of zero, one, multiple or all of their array elements or member values, respectively. Applied to other value types, it will select nothing. A relative path, beginning with @, refers to the current array element or member value as the filter //PICKER// iterates over the array or object.
Existence Tests A singular path by itself in a Boolean context is an existence test which yields true if the path selects a node and yields false if the path does not select a node. This existence test — as an exception to the general rule — also works with nodes with structured values. To test the value of a node selected by a path, an explicit comparison is necessary. For example, to test whether the node selected by the path @.foo has the value null, use @.foo == null (see ) rather than the negated existence test !@.foo (which yields false if @.foo selects a node, regardless of the node's value).
Comparisons The comparison operators ==, <, and > are defined first and then these are used to define !=, <=, and >=. When a path resulting in an empty nodelist appears on either side of a comparison: a comparison using the operator == yields true if and only if the comparison is between two paths each of which result in an empty nodelist. a comparison using either of the operators < or > yields false. When any path on either side of a comparison results in a nodelist consisting of a single node, each such path is replaced by the value of its node and then: a comparison using the operator == yields true if and only if the comparison is between: values of the same primitive type (numbers, strings, booleans, and null) which are equal, equal arrays, that is arrays of the same length where each element of the first array is equal to the corresponding element of the second array, or equal objects with no duplicate names, that is where: both objects have the same collection of names (with no duplicates), and for each of those names, the values associated with the name by the objects are equal. a comparison using either of the operators < or > yields true if and only if the comparison is between values of the same type which are both numbers or both strings and which satisfy the comparison: numbers expected to interoperate as per I-JSON MUST compare using the normal mathematical ordering; numbers not expected to interoperate as per I-JSON MAY compare using an implementation specific ordering the empty string compares less than any non-empty string a non-empty string compares less than another non-empty string if and only if the first string starts with a lower Unicode scalar value than the second string or if both strings start with the same Unicode scalar value and the remainder of the first string compares less than the remainder of the second string. Note that comparisons using either of the operators < or > yield false if either value being compared is an object, array, boolean, or null. !=, <= and >= are defined in terms of the other comparison operators. For any a and b: The comparison a != b yields true if and only if a == b yields false. The comparison a <= b yields true if and only if a < b yields true or a == b yields true. The comparison a >= b yields true if and only if a > b yields true or a == b yields true.
Regular Expressions A regular-expression test yields true if and only if the value on the left-hand side of =~ is a string value and it matches the regular expression on the right-hand side according to the semantics of . The semantics of regular expressions are as defined in .
Boolean Operators The logical AND, OR, and NOT operators have the normal semantics of Boolean algebra and obey its laws (see, for example, ).
Examples JSON:
Comparison Result Comment $.absent1 == $.absent2 true Empty nodelists $.absent1 <= $.absent2 true == implies <= $.absent == 'g' false Empty nodelist $.absent1 != $.absent2 false Empty nodelists $.absent != 'g' true Empty nodelist 1 <= 2 true Numeric comparison 1 > 2 false Strict, numeric comparison 13 == '13' false Type mismatch 'a' <= 'b' true String comparison 'a' > 'b' false Strict, string comparison $.obj == $.arr false Type mismatch $.obj != $.arr true Type mismatch $.obj == $.obj true Object comparison $.obj != $.obj false Object comparison $.arr == $.arr true Array comparison $.arr != $.arr false Array comparison $.obj == 17 false Type mismatch $.obj != 17 true Type mismatch $.obj <= $.arr false Objects and arrays are not ordered $.obj < $.arr false Objects and arrays are not ordered $.obj <= $.obj true == implies <= $.arr <= $.arr true == implies <= 1 <= $.arr false Arrays are not ordered 1 >= $.arr false Arrays are not ordered 1 > $.arr false Arrays are not ordered 1 < $.arr false Arrays are not ordered true <= true true == implies <= true > true false Booleans are not ordered JSON:
Queries: Query Result Result Paths Comment $.a[?@>3.5] 5
4
6
$['a'][1]
$['a'][4]
$['a'][5]
Array value comparison $.a[?@.b] {"b": "j"}
{"b": "k"}
$['a'][6]
$['a'][7]
Array value existence $.a[?@<2 || @.b == "k"] 1
{"b": "k"}
$['a'][2]
$['a'][7]
Array value logical OR $.a[?@.b =~ "i.*"] {"b": "j"}
{"b": "k"}
$['a'][6]
$['a'][7]
Array value regular expression $.o[?@>1 && @<4] 2
3
$['o']['q']
$['o']['r']
Object value logical AND $.o[?@>1 && @<4] 3
2
$['o']['r']
$['o']['q']
Alternative result $.o[?@.u || @.x] {"u": 6} $['o']['t'] Object value logical OR $.a[?(@.b == $.x)] 3
5
1
2
4
6
$['a'][0]
$['a'][1]
$['a'][2]
$['a'][3]
$['a'][4]
Comparison of paths with no values $[?(@ == @)]     Comparison of structured values
Descendant Selectors
Syntax The descendant selectors start with a double dot .. followed by either a wildcard selector (descendant-wild-selector) or a child selector (descendant-child-selector).
descendant-wild and descendant-wild-shorthand may be used interchangeably. descendant-name-shorthand is a shorthand notation for the occasion when a descendant child selector is used with a single name //PICKER// where the name can be used in its shorthand notation. The shorthand is not valid for child selectors containing more than one //PICKER// other //PICKER// types, or name //PICKERS// that cannot themselves be represented in shorthand. Note that .. on its own is not a valid selector.
Semantics A descendant selector selects zero or more descendants of a node. A nodelist enumerating the descendants is known as a descendant nodelist when: nodes of any array appear in array order, nodes appear immediately before all their descendants. This definition does not stipulate the order in which the children of an object appear, since JSON objects are unordered. The resultant nodelist of a descendant selector is the result of applying a selector (or no selector), depending on the variant of the descendant selector, to a descendant nodelist, as shown below: Variant Selector to apply Comment ..[*] none All descendants, recursively ..[<//PICKERS//>] [<//PICKERS//>] Child selector
Examples JSON:
Queries: Query Result Result Paths Comment $..j 1
4
$['o']['j']
$['a'][2][0]['j']
Object values $..j 4
1
$['a'][2][0]['j']
$['o']['j']
Alternative result $..[0] 5
{"j": 4}
$['a'][0]
$['a'][2][0]
Array values $..[0] {"j": 4}
5
$['a'][2][0]
$['a'][0]
Alternative result $..[*]
$..*
{"j": 1, "k" : 2}
[5, 3, [{"j": 4}]]
1
2
5
3
[{"j": 4}]
{"j": 4}
4
$['o']
$['a']
$['o']['j']
$['o']['k']
$['a'][0]
$['a'][1]
$['a'][2]
$['a'][2][0]
$['a'][2][0]['j']
All values
Note: The ordering of the results for the $..[*] and $..* examples above is not guaranteed, except that: {"j": 1, "k": 2} must appear before 1 and 2, [5, 3, [{"j": 4}]] must appear before 5, 3, and [{"j": 4}], 5 must appear before 3 which must appear before [{"j": 4}], 5 and 3 must appear before {"j": 4} and 4, [{"j": 4}] must appear before {"j": 4}, and {"j": 4} must appear before 4.
Semantics of null Note that JSON null is treated the same as any other JSON value: it is not taken to mean "undefined" or "missing".
Examples JSON:
Queries: Query Result Result Paths Comment $.a null $['a'] Object value $.a[0]     null used as array $.a.d     null used as object $.b[0] null $['b'][0] Array value $.b[*] null $['b'][0] Array value $.b[?@] null $['b'][0] Existence $.b[?@==null] null $['b'][0] Comparison $.c[?(@.d==null)]     Comparison with "missing" value $.null 1 $['null'] Not JSON null at all, just a string as object key
Normalized Paths A Normalized Path is a JSONPath with restricted syntax that identifies a node by providing a query that results in exactly that node. For example, the JSONPath expression $.book[?(@.price<10)] could select two values with Normalized Paths $['book'][3] and $['book'][5]. For a given JSON value, there is a one to one correspondence between the value's nodes and the Normalized Paths that identify these nodes. A JSONPath implementation may output Normalized Paths instead of, or in addition to, the values identified by these paths. Since bracket notation is more general than dot notation, it is used to construct Normalized Paths. Single quotes are used to delimit string member names. This reduces the number of characters that need escaping when Normalized Paths appear as strings (which are delimited with double quotes) in JSON texts. Certain characters are escaped, in one and only one way; all other characters are unescaped. Normalized Paths are Singular Paths. Not all Singular Paths are Normalized Paths: $[-3], for example, is a Singular Path, but not a Normalized Path.
Examples Path Normalized Path Comment $.a $['a'] Object value $[1] $[1] Array index $.a.b[1:2] $['a']['b'][1] Nested structure $["\u000B"] $['\u000b'] Unicode escape $["\u0061"] $['a'] Unicode character $["\u00b1"] $['±'] Unicode character $["\u00b1"] is normalized into (noise in the table and lack of typewriter font is due to RFCXMLv3 limitations).
IANA Considerations
Registration of Media Type application/jsonpath IANA is requested to register the following media type :
Type name:
application
Subtype name:
jsonpath
Required parameters:
N/A
Optional parameters:
N/A
Encoding considerations:
binary (UTF-8)
Security considerations:
See the Security Considerations section of RFCXXXX.
Interoperability considerations:
N/A
Published specification:
RFCXXXX
Applications that use this media type:
Applications that need to convey queries in JSON data
Fragment identifier considerations:
N/A
Additional information:
Deprecated alias names for this type:
N/A
Magic number(s):
N/A
File extension(s):
N/A
Macintosh file type code(s):
N/A
Person & email address to contact for further information: iesg@ietf.org
Intended usage:
COMMON
Restrictions on usage:
N/A
Author:
JSONPath WG
Change controller:
IESG
Provisional registration? (standards tree only):
no
Security Considerations Security considerations for JSONPath can stem from attack vectors on JSONPath implementations, and the way JSONPath is used in security-relevant mechanisms.
Attack vectors on JSONPath Implementations Historically, JSONPath has often been implemented by feeding parts of the query to an underlying programming language engine, e.g., JavaScript. This approach is well known to lead to injection attacks and would require perfect input validation to prevent these attacks (see for similar considerations for JSON itself). Instead, JSONPath implementations need to implement the entire syntax of the query without relying on the parsers of programming language engines. Attacks on availability may attempt to trigger unusually expensive runtime performance exhibited by certain implementations in certain cases. (See for issues in hash-table implementations, and for performance issues in regular expression implementations.) Implementers need to be aware that good average performance is not sufficient as long as an attacker can choose to submit specially crafted JSONPath queries or arguments that trigger surprisingly high, possibly exponential, CPU usage or, for example via a naive recursive implementation of the descendant selector, stack overflow. Implementations need to have appropriate resource management to mitigate these attacks.
Attacks on Security Mechanisms that Employ JSONPath Where JSONPath is used as a part of a security mechanism, attackers can attempt to provoke unexpected or unpredictable behavior, or take advantage of differences in behavior between JSONPath implementations. Unexpected or unpredictable behavior can arise from an argument with certain constructs described as unpredictable by . Predictable behavior can be expected, except in relation to the ordering of objects, for any argument conforming with . Other attacks can target the behavior of underlying technologies such as UTF-8 (see ) and the Unicode character set.
UTF-8, a transformation format of ISO 10646 ISO/IEC 10646-1 defines a large character set called the Universal Character Set (UCS) which encompasses most of the world's writing systems. The originally proposed encodings of the UCS, however, were not compatible with many current applications and protocols, and this has led to the development of UTF-8, the object of this memo. UTF-8 has the characteristic of preserving the full US-ASCII range, providing compatibility with file systems, parsers and other software that rely on US-ASCII values but are transparent to other values. This memo obsoletes and replaces RFC 2279. Augmented BNF for Syntax Specifications: ABNF Internet technical specifications often need to define a formal syntax. Over the years, a modified version of Backus-Naur Form (BNF), called Augmented BNF (ABNF), has been popular among many Internet specifications. The current specification documents ABNF. It balances compactness and simplicity with reasonable representational power. The differences between standard BNF and ABNF involve naming rules, repetition, alternatives, order-independence, and value ranges. This specification also supplies additional rule definitions and encoding for a core lexical analyzer of the type common to several Internet specifications. [STANDARDS-TRACK] The JavaScript Object Notation (JSON) Data Interchange Format JavaScript Object Notation (JSON) is a lightweight, text-based, language-independent data interchange format. It was derived from the ECMAScript Programming Language Standard. JSON defines a small set of formatting rules for the portable representation of structured data.This document removes inconsistencies with other specifications of JSON, repairs specification errors, and offers experience-based interoperability guidance. The I-JSON Message Format I-JSON (short for "Internet JSON") is a restricted profile of JSON designed to maximize interoperability and increase confidence that software can process it successfully with predictable results. Media Type Specifications and Registration Procedures This document defines procedures for the specification and registration of media types for use in HTTP, MIME, and other Internet protocols. This memo documents an Internet Best Current Practice. I-Regexp: An Interoperable Regexp Format Universität Bremen TZI Textuality This document specifies I-Regexp, a flavor of regular expressions that is limited in scope with the goal of interoperation across many different regular-expression libraries. The Unicode® Standard: Version 14.0 - Core Specification The Unicode Consortium Key words for use in RFCs to Indicate Requirement Levels In many standards track documents several words are used to signify the requirements in the specification. These words are often capitalized. This document defines these words as they should be interpreted in IETF documents. This document specifies an Internet Best Current Practices for the Internet Community, and requests discussion and suggestions for improvements. Ambiguity of Uppercase vs Lowercase in RFC 2119 Key Words RFC 2119 specifies common key words that may be used in protocol specifications. This document aims to reduce the ambiguity by clarifying that only UPPERCASE usage of the key words have the defined special meanings. JavaScript Object Notation (JSON) Pointer JSON Pointer defines a string syntax for identifying a specific value within a JavaScript Object Notation (JSON) document. JSONPath — XPath for JSON Fachhochschule Dortmund XML Path Language (XPath) 2.0 (Second Edition) Information technology — ECMAScript for XML (E4X) specification ISO Slice notation ECMAScript Language Specification, Standard ECMA-262, Third Edition Ecma International Concise Binary Object Representation (CBOR) The Concise Binary Object Representation (CBOR) is a data format whose design goals include the possibility of extremely small code size, fairly small message size, and extensibility without the need for version negotiation. These design goals make it different from earlier binary serializations such as ASN.1 and MessagePack.This document obsoletes RFC 7049, providing editorial improvements, new details, and errata fixes while keeping full compatibility with the interchange format of RFC 7049. It does not create a new version of the format. Boolean algebra laws
Inspired by XPath This appendix is informative. At the time JSONPath was invented, XML was noted for the availability of powerful tools to analyze, transform and selectively extract data from XML documents. is one of these tools. In 2007, the need for something solving the same class of problems for the emerging JSON community became apparent, specifically for: Finding data interactively and extracting them out of JSON values without special scripting. Specifying the relevant parts of the JSON data in a request by a client, so the server can reduce the amount of data in its response, minimizing bandwidth usage. (Note that XPath has evolved since 2007, and recent versions even nominally support operating inside JSON values. This appendix only discusses the more widely used version of XPath that was available in 2007.) JSONPath picks up the overall feeling of XPath, but maps the concepts to syntax (and partially semantics) that would be familiar to someone using JSON in a dynamic language. E.g., in popular dynamic programming languages such as JavaScript, Python and PHP, the semantics of the XPath expression
can be realized in the expression
or, in bracket notation,
with the variable x holding the argument. The JSONPath language was designed to: be naturally based on those language characteristics; cover only the most essential parts of XPath 1.0; be lightweight in code size and memory consumption; be runtime efficient.
JSONPath and XPath JSONPath expressions apply to JSON values in the same way as XPath expressions are used in combination with an XML document. JSONPath uses $ to refer to the root node of the argument, similar to XPath's / at the front. JSONPath expressions move further down the hierarchy using dot notation ($.store.book[0].title) or the bracket notation ($['store']['book'][0]['title']), a lightweight/limited, and a more heavyweight syntax replacing XPath's / within query expressions. Both JSONPath and XPath use * for a wildcard. The descendant operators, starting with .., borrowed from , are similar to XPath's //. The array slicing construct [start:end:step] is unique to JSONPath, inspired by from ECMASCRIPT 4. Filter expressions are supported via the syntax ?(<boolean expr>) as in
extends by providing a comparison with similar XPath concepts. XPath JSONPath Description / $ the root XML element . @ the current XML element / . or [] child operator .. n/a parent operator // ..name, ..[index], ..*, or ..[*] descendants (JSONPath borrows this syntax from E4X) * * wildcard: All XML elements regardless of their names @ n/a attribute access: JSON values do not have attributes [] [] subscript operator used to iterate over XML element collections and for predicates ¦ [,] Union operator (results in a combination of node sets); called list operator in JSONPath, allows combining member names, array indices, and slices n/a [start:end:step] array slice operator borrowed from ES4 [] ?() applies a filter (script) expression seamless n/a expression engine () n/a grouping For further illustration, shows some XPath expressions and their JSONPath equivalents. 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 prices of everything in the store //book[3] $..book[2] the third book //book[last()] $..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 cheaper than 10 //* $..* all elements in XML document; all member values and array elements contained in input value
XPath has a lot more functionality (location paths in unabbreviated syntax, operators and functions) than listed in this comparison. Moreover, there are significant differences in how the subscript operator works in XPath and JSONPath: Square brackets in XPath expressions always operate on the node set resulting from the previous path fragment. Indices always start at 1. With JSONPath, square brackets operate on the object or array addressed by the previous path fragment. Array indices always start at 0.
JSON Pointer This appendix is informative. JSONPath is not intended as a replacement for, but as a more powerful companion to, JSON Pointer . The purposes of the two standards are different. JSON Pointer is for identifying a single value within a JSON value whose structure is known. JSONPath can identify a single value within a JSON value, for example by using a Normalized Path. But JSONPath is also a query syntax that can be used to search for and extract multiple values from JSON values whose structure is known only in a general way. A Normalized JSONPath can be converted into a JSON Pointer by converting the syntax, without knowledge of any JSON value. The inverse is not generally true: a numeric path component in a JSON Pointer may identify a member of a JSON object or may index an array. For conversion to a JSONPath query, knowledge of the structure of the JSON value is needed to distinguish these cases.
Acknowledgements This specification is based on 's original online article defining JSONPath . The books example was taken from http://coli.lili.uni-bielefeld.de/~andreas/Seminare/sommer02/books.xml — a dead link now.
Contributors InfluxData, Inc.
Pisa IT mmikulicic@gmail.com
TheSoul Publishing Ltd.
Limassol Cyprus esurov.tsp@gmail.com