Esta sección proporciona detalles de la funcionalidad JSONPath admitida en los pasos de preprocesamiento del valor de la métrica.
JSONPath consta de segmentos separados por puntos. Un segmento puede ser tanto una palabra simple como el nombre de un valor JSON, *
o una construcción más compleja encerrada entre corchetes [
]
. El punto separador antes del segmento de soporte es opcional y se puede omitir. Por ejemplo:
Ruta | Descripción |
---|---|
$.object.name |
Devuelve el contenido del object.name. |
$.object['name'] |
Devuelve el contenido de object.name. |
$.object.['name'] |
Devuelve el contenido de object.name. |
$["object"]['name'] |
Devuelve el contenido de object.name. |
$.['object'].["name"] |
Devuelve el contenido de object.name. |
$.object.history.length() |
Devuelve el número de elementos de la matriz object.history. |
$[?(@.name == 'Object')].price.first() |
Devuelve el campo de precio del primer objeto con nombre 'Object'. |
$[?(@.name == 'Object')].history.first().length() |
Devuelve el número de elementos de la matriz histórica del primer objeto con nombre 'Object'. |
$[?(@.price > 10)].length() |
Devuelve el número de objetos con un precio mayor que 10. |
Ver también: Escapar caracteres especiales de valores de macro LLD en JSONPath.
Segment | Description |
---|---|
<name> |
Match object property by name. |
* |
Match all object properties. |
['<name>'] |
Match object property by name. |
['<name>', '<name>', ...] |
Match object property by any of the listed names. |
[<index>] |
Match array element by the index. |
[<number>, <number>, ...] |
Match array element by any of the listed indexes. |
[*] |
Match all object properties or array elements. |
[<start>:<end>] |
Match array elements by the defined range: <start> - the first index to match (including). If not specified matches all array elements from the beginning. If negative specifies starting offset from the end of array. <end> - the last index to match (excluding). If not specified matches all array elements to the end. If negative specifies starting offset from the end of array. |
[?(<expression>)] |
Match objects/array elements by applying filter expression. |
To find a matching segment ignoring its ancestry (detached segment) it must be prefixed with '..' , for example $..name
or $..['name']
return values of all 'name' properties.
Matched element names can be extracted by adding a ~
suffix to the JSONPath. It returns the name of the matched object or an index in string format of the matched array item. The output format follows the same rules as other JSONPath queries - definite path results are returned 'as is' and indefinite path results are returned in array. However there is not much point of extracting the name of an element matching a definite path - it's already known.
Filter expression is a arithmetical expression in infix notation.
Supported operands:
Operand | Description | Example |
---|---|---|
"<text>" '<text>' |
Text constant. | 'value: \'1\'' "value: '1'" |
<number> |
Numeric constant supporting scientific notation. | 123 |
<jsonpath starting with $> |
Value referred to by the JSONPath from the input document root node; only definite paths are supported. | $.object.name |
<jsonpath starting with @> |
Value referred to by the JSONPath from the current object/element; only definite paths are supported. | @.name |
Supported operators:
Operator | Type | Description | Result |
---|---|---|---|
- |
binary | Subtraction. | Number. |
+ |
binary | Addition. | Number. |
/ |
binary | Division. | Number. |
* |
binary | Multiplication. | Number. |
== |
binary | Is equal to. | Boolean (1 or 0). |
!= |
binary | Is not equal to. | Boolean (1 or 0). |
< |
binary | Is less than. | Boolean (1 or 0). |
<= |
binary | Is less than or equal to. | Boolean (1 or 0). |
> |
binary | Is greater than. | Boolean (1 or 0). |
>= |
binary | Is greater than or equal to. | Boolean (1 or 0). |
=~ |
binary | Matches regular expression. | Boolean (1 or 0). |
! |
unary | Boolean not. | Boolean (1 or 0). |
\|\| |
binary | Boolean or. | Boolean (1 or 0). |
&& |
binary | Boolean and. | Boolean (1 or 0). |
Las funciones se pueden utilizar al final de JSONPath. Múltiples funciones pueden ser encadenadas si la función anterior devuelve un valor aceptado por la siguiente función.
Funciones soportadas:
Función | Descripción | Entrada | Salida |
---|---|---|---|
avg |
Valor promedio de números en la matriz de entrada. | Matriz de números. | Número. |
min |
Valor mínimo de números en la matriz de entrada. | Matriz de números. | Número. |
max |
Valor máximo de números en la matriz de entrada. | Matriz de números. | Número. |
sum |
Suma de números en la matriz de entrada. | Matriz de números. | Número. |
length |
Número de elementos en la matriz de entrada. | Matriz. | Número. |
first |
El primer elemento de la matriz. | Matriz. | Una construcción JSON (objeto, matriz, valor) que depende del contenido de la matriz de entrada. |
Los valores numéricos citados son aceptados por las funciones agregadas JSONPath. Significa que los valores se convierten de tipo cadena a numérico si se requiere agregación.
Una entrada incompatible hará que la función genere un error.
JSONPaths se puede dividir en rutas definidas e indefinidas. Una ruta definida puede devolver solo un valor nulo o una única coincidencia. Una ruta indefinida puede devolver múltiples coincidencias, básicamente segmentos JSONPaths con múltiples y separadas listas de nombres/índices, segmentos de matriz o segmentos de expresión. Sin embargo, cuando se utiliza la función, JSONPath se vuelve definido, como siempre lo hacen las funciones de salida de valor único.
Una ruta definida devuelve el objeto/matriz/valor al que hace referencia, mientras que una ruta indefinida devuelve una matriz de objetos/matrices/valores coincidentes.
Es posible que el orden de las propiedades en los resultados de la consulta JSONPath no se alinee con el orden de las propiedades JSON originales debido a los métodos de optimización internos. Por ejemplo, JSONPath $.books[1]["autor", "título"]
puede devolver ["título", "autor"]
. Si es esencial preservar el orden de la propiedad original, se deben considerar métodos alternativos de procesamiento posterior a la consulta.
Los espacios en blanco (espacios, caracteres de tabulación) se pueden utilizar libremente notación y expresiones de segmentos entre paréntesis, por ejemplo, $[ 'a' ][ 0 ][ ?( $.b == 'c' ) ][ : -1 ].first()
.
Las cadenas deben estar entre comillas simples ' o dobles ". Dentro de las cadenas, las comillas simples o dobles (dependiendo de cuáles se utilicen para encerrar la cadena) y las barras invertidas \
se escapan con el carácter de barra invertida \
.
{
"books": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95,
"id": 1
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99,
"id": 2
},
{
"category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99,
"id": 3
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99,
"id": 4
}
],
"services": {
"delivery": {
"servicegroup": 1000,
"description": "Next day delivery in local town",
"active": true,
"price": 5
},
"bookbinding": {
"servicegroup": 1001,
"description": "Printing and assembling book in A5 format",
"active": true,
"price": 154.99
},
"restoration": {
"servicegroup": 1002,
"description": "Various restoration methods",
"active": false,
"methods": [
{
"description": "Checmical cleaning",
"price": 46
},
{
"description": "Pressing pages damaged by moisture",
"price": 24.5
},
{
"description": "Rebinding torn book",
"price": 99.49
}
]
}
},
"filters": {
"price": 10,
"category": "fiction",
"no filters": "no \"filters\""
},
"closed message": "Store is closed",
"tags": [
"a",
"b",
"c",
"d",
"e"
]
}
JSONPath | Type | Result | Comments |
---|---|---|---|
$.filters.price |
definite | 10 | |
$.filters.category |
definite | fiction | |
$.filters['no filters'] |
definite | no "filters" | |
$.filters |
definite | { "price": 10, "category": "fiction", "no filters": "no \"filters\"" } |
|
$.books[1].title |
definite | Sword of Honour | |
$.books[-1].author |
definite | J. R. R. Tolkien | |
$.books.length() |
definite | 4 | |
$.tags[:] |
indefinite | ["a", "b", "c", "d", "e" ] | |
$.tags[2:] |
indefinite | ["c", "d", "e" ] | |
$.tags[:3] |
indefinite | ["a", "b", "c"] | |
$.tags[1:4] |
indefinite | ["b", "c", "d"] | |
$.tags[-2:] |
indefinite | ["d", "e"] | |
$.tags[:-3] |
indefinite | ["a", "b"] | |
$.tags[:-3].length() |
definite | 2 | |
$.books[0, 2].title |
indefinite | ["Sayings of the Century", "Moby Dick"] | |
$.books[1]['author', "title"] |
indefinite | ["Evelyn Waugh", "Sword of Honour"] | |
$..id |
indefinite | [1, 2, 3, 4] | |
$.services..price |
indefinite | [5, 154.99, 46, 24.5, 99.49] | |
$.books[?(@.id == 4 - 0.4 * 5)].title |
indefinite | ["Sword of Honour"] | This query shows that arithmetical operations can be used in queries. Of course this query can be simplified to $.books[?(@.id == 2)].title |
$.books[?(@.id == 2 \|\| @.id == 4)].title |
indefinite | ["Sword of Honour", "The Lord of the Rings"] | |
$.books[?(!(@.id == 2))].title |
indefinite | ["Sayings of the Century", "Moby Dick", "The Lord of the Rings"] | |
$.books[?(@.id != 2)].title |
indefinite | ["Sayings of the Century", "Moby Dick", "The Lord of the Rings"] | |
$.books[?(@.title =~ " of ")].title |
indefinite | ["Sayings of the Century", "Sword of Honour", "The Lord of the Rings"] | |
$.books[?(@.price > 12.99)].title |
indefinite | ["The Lord of the Rings"] | |
$.books[?(@.author > "Herman Melville")].title |
indefinite | ["Sayings of the Century", "The Lord of the Rings"] | |
$.books[?(@.price > $.filters.price)].title |
indefinite | ["Sword of Honour", "The Lord of the Rings"] | |
$.books[?(@.category == $.filters.category)].title |
indefinite | ["Sword of Honour","Moby Dick","The Lord of the Rings"] | |
$..[?(@.id)] |
indefinite | [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95, "id": 1 }, { "category": "fiction", "author": "Evelyn Waugh", "title": "Sword of Honour", "price": 12.99, "id": 2 }, { "category": "fiction", "author": "Herman Melville", "title": "Moby Dick", "isbn": "0-553-21311-3", "price": 8.99, "id": 3 }, { "category": "fiction", "author": "J. R. R. Tolkien", "title": "The Lord of the Rings", "isbn": "0-395-19395-8", "price": 22.99, "id": 4 } ] |
|
$.services..[?(@.price > 50)].description |
indefinite | '["Printing and assembling book in A5 format", "Rebinding torn book"] | |
$..id.length() |
definite | 4 | |
$.books[?(@.id == 2)].title.first() |
definite | Sword of Honour | |
$..tags.first().length() |
definite | 5 | $..tags is indefinite path, so it returns an array of matched elements - [["a", "b", "c", "d", "e" ]], first() returns the first element - ["a", "b", "c", "d", "e" ] and finally length() calculates its length - 5. |
$.books[*].price.min() |
definite | 8.95 | |
$..price.max() |
definite | 154.99 | |
$.books[?(@.category == "fiction")].price.avg() |
definite | 14.99 | |
$.books[?(@.category == $.filters.xyz)].title |
indefinite | A query without match returns NULL for definite and indefinite paths. | |
$.services[?(@.active=="true")].servicegroup |
indefinite | [1000,1001] | Text constants must be used in boolean value comparisons. |
$.services[?(@.active=="false")].servicegroup |
indefinite | [1002] | Text constants must be used in boolean value comparisons. |
$.services[?(@.servicegroup=="1002")]~.first() |
definite | restoration |