Atitit json数据查询法 jsonpath
目录
XML的优点之一是处理的可用性-包括XPath-它被定义为W3C标准。对于JSON,出现了一个类似的名为JSONPath的工具。
本文将介绍Jayway JsonPath,它是JSONPath规范的Java实现。它描述了设置,语法,通用API以及用例的演示。
在JsonPath中,我们有几个有用的运算符:
根节点($):此符号表示JSON结构的根成员,无论它是对象还是数组。它的用法示例包含在前面的小节中。
当前节点(@):表示正在处理的节点,通常用作谓词的输入表达式的一部分。假设我们在上面的JSON文档中处理book数组,表达式book [?(@。price == 49.99)]引用该数组中的第一本书。
通配符(*):表示指定范围内的所有元素。例如,book [*]表示book数组内的所有节点
以$为root,.操作符或[]索引的方式获取指定 JsonPath 数据
-
- # JSONPath expressions
JSONPath expressions always refer to a JSON structure in the same way as XPath expression are used in combination with an XML document. Since a JSON structure is usually anonymous and doesn't necessarily have a "root member object" JSONPath assumes the abstract name $ assigned to the outer level object.
JSONPath expressions can use the dot–notation
$.store.book[0].title
or the bracket–notation
$['store']['book'][0]['title']
for input pathes. Internal or output pathes 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] from ECMASCRIPT 4.
Expressions of the underlying scripting language (<expr>) can be used as an alternative to explicit names or indices as in
$.store.book[(@.length-1)].title
using the symbol '@' 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 |
// |
.. |
recursive descent. JSONPath borrows this syntax from E4X. |
* |
* |
wildcard. All objects/elements regardless their names. |
@ |
n/a |
attribute access. JSON structures 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 |