GitHub - json-path/JsonPath: Java JsonPath implementation json 类xpath 解析工具

标签: github json path | 发表时间:2017-10-19 20:22 | 作者:

Jayway JsonPath

A Java DSL for reading JSON documents.

Build StatusMaven CentralJavadoc

Jayway JsonPath is a Java port ofStefan Goessner JsonPath implementation.


05 Jul 2017 - Released JsonPath 2.4.0

26 Jun 2017 - Released JsonPath 2.3.0

29 Feb 2016 - Released JsonPath 2.2.0

22 Nov 2015 - Released JsonPath 2.1.0

19 Mar 2015 - Released JsonPath 2.0.0

11 Nov 2014 - Released JsonPath 1.2.0

01 Oct 2014 - Released JsonPath 1.1.0

26 Sep 2014 - Released JsonPath 1.0.0

Getting Started

JsonPath is available at the Central Maven Repository. Maven users add this to your POM.


If you need help ask questions atStack Overflow. Tag the question 'jsonpath' and 'java'.

JsonPath expressions always refer to a JSON structure in the same way as XPath expression are used in combination with an XML document. The "root member object" in JsonPath is always referred to as$regardless if it is an object or array.

JsonPath expressions can use the dot–notation


or the bracket–notation



$The root element to query. This starts all path expressions.
@The current node being processed by a filter predicate.
*Wildcard. Available anywhere a name or numeric are required.
..Deep scan. Available anywhere a name is required.
.<name>Dot-notated child
['<name>' (, '<name>')]Bracket-notated child or children
[<number> (, <number>)]Array index or indexes
[start:end]Array slice operator
[?(<expression>)]Filter expression. Expression must evaluate to a boolean value.


Functions can be invoked at the tail end of a path - the input to a function is the output of the path expression. The function output is dictated by the function itself.

min()Provides the min value of an array of numbersDouble
max()Provides the max value of an array of numbersDouble
avg()Provides the average value of an array of numbersDouble
stddev()Provides the standard deviation value of an array of numbersDouble
length()Provides the length of an arrayInteger

Filter Operators

Filters are logical expressions used to filter arrays. A typical filter would be[?(@.age > 18)]where@represents the current item being processed. More complex filters can be created with logical operators&&and||. String literals must be enclosed by single or double quotes ([?(@.color == 'blue')]or[?(@.color == "blue")]).

==left is equal to right (note that 1 is not equal to '1')
!=left is not equal to right
<left is less than right
<=left is less or equal to right
>left is greater than right
>=left is greater than or equal to right
=~left matches regular expression [?( =~ /foo.*?/i)]
inleft exists in right [?(@.size in ['S', 'M'])]
ninleft does not exists in right
subsetofleft is a subset of right [?(@.sizes subsetof ['S', 'M', 'L'])]
sizesize of left (array or string) should match right
emptyleft (array or string) should be empty

Path Examples

Given the json

            {"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":8.95},
            {"category":"fiction","author":"Evelyn Waugh","title":"Sword of Honour","price":12.99},
            {"category":"fiction","author":"Herman Melville","title":"Moby Dick","isbn":"0-553-21311-3","price":8.99},
            {"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22.99}
JsonPath (click link to try)Result
$[*].authorThe authors of all books
$..authorAll authors
$.store.*All things, both books and bicycles
$.store..priceThe price of everything
$[2]The third book
$[-2]The second to last book
$[0,1]The first two books
$[:2]All books from index 0 (inclusive) until index 2 (exclusive)
$[1:2]All books from index 1 (inclusive) until index 2 (exclusive)
$[-2:]Last two books
$[2:]Book number two from tail
$[?(@.isbn)]All books with an ISBN number
$[?(@.price < 10)]All books in store cheaper than 10
$[?(@.price <= $['expensive'])]All books in store that are not "expensive"
$[?( =~ /.*REES/i)]All books matching regex (ignore case)
$..*Give me every thing
$ number of books

Reading a Document

The simplest most straight forward way to use JsonPath is via the static read API.


If you only want to read once this is OK. In case you need to read an other path as well this is not the way to go since the document will be parsed every time you call To avoid the problem you can parse the json first.


JsonPath also provides a fluent API. This is also the most flexible one.

                            .read("$[?(@.price > 10)]",List.class);

What is Returned When?

When using JsonPath in java its important to know what type you expect in your result. JsonPath will automatically try to cast the result to the type expected by the invoker.

//Will throw an java.lang.ClassCastExceptionList<String>list=JsonPath.parse(json).read("$[0].author")//Works fineStringauthor=JsonPath.parse(json).read("$[0].author")

When evaluating a path you need to understand the concept of when a path isdefinite. A path isindefiniteif it contains:

  • ..- a deep scan operator
  • ?(<expression>)- an expression
  • [<number>, <number> (, <number>)]- multiple array indexes

Indefinitepaths always returns a list (as represented by current JsonProvider).

By default a simple object mapper is provided by the MappingProvider SPI. This allows you to specify the return type you want and the MappingProvider will try to perform the mapping. In the example below mapping betweenLongandDateis demonstrated.

Stringjson="{\"date_as_long\": 1411455611975}";Datedate=JsonPath.parse(json).read("$['date_as_long']",Date.class);

If you configure JsonPath to useJacksonMappingProvideror GsonMappingProvider` you can even map your JsonPath output directly into POJO's.


To obtainin full generics type information, use TypeRef.

TypeRef<List<String>>typeRef=newTypeRef<List<String>>() {};List<String>titles=JsonPath.parse(JSON_DOCUMENT).read("$[*].title", typeRef);


There are three different ways to create filter predicates in JsonPath.

Inline Predicates

Inline predicates are the ones defined in the path.

                                     .read("$[?(@.price < 10)]");

You can use&&and||to combine multiple predicates[?(@.price < 10 && @.category == 'fiction')],[?(@.category == 'reference' || @.price > 10)].

You can use!to negate a predicate[?(!(@.price < 10 && @.category == 'fiction'))].

Filter Predicates

Predicates can be built using the Filter API as shown below:

import staticcom.jayway.jsonpath.JsonPath.parse;import staticcom.jayway.jsonpath.Criteria.where;import staticcom.jayway.jsonpath.Filter.filter;......FiltercheapFictionFilter=filter(
);List<Map<String,Object>>books=parse(json).read("$[?]", cheapFictionFilter);

Notice the placeholder?for the filter in the path. When multiple filters are provided they are applied in order where the number of placeholders must match the number of provided filters. You can specify multiple predicate placeholders in one filter operation[?, ?], both predicates must match.

Filters can also be combined with 'OR' and 'AND'


Roll Your Own

Third option is to implement your own predicates

PredicatebooksWithISBN=newPredicate() {@Overridepublicbooleanapply(PredicateContextctx) {returnctx.item(Map.class).containsKey("isbn");
};List<Map<String,Object>>"$[?].isbn",List.class, booksWithISBN);

Path vs Value

In the Goessner implementation a JsonPath can return eitherPathorValue.Valueis the default and what all the examples above are returning. If you rather have the path of the elements our query is hitting this can be acheived with an option.



Tweaking Configuration


When creating your Configuration there are a few option flags that can alter the default behaviour.


This option makes JsonPath return null for missing leafs. Consider the following json

Configurationconf=Configuration.defaultConfiguration();//Works fineStringgender0=JsonPath.using(conf).parse(json).read("$[0]['gender']");//PathNotFoundException thrownStringgender1=JsonPath.using(conf).parse(json).read("$[1]['gender']");Configurationconf2=conf.addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL);//Works fineStringgender0=JsonPath.using(conf2).parse(json).read("$[0]['gender']");//Works fine (null is returned)Stringgender1=JsonPath.using(conf2).parse(json).read("$[1]['gender']");


This option configures JsonPath to return a list even when the path isdefinite.

Configurationconf=Configuration.defaultConfiguration();//Works fineList<String>genders0=JsonPath.using(conf).parse(json).read("$[0]['gender']");//PathNotFoundException thrownList<String>genders1=JsonPath.using(conf).parse(json).read("$[1]['gender']");


This option makes sure no exceptions are propagated from path evaluation. It follows these simple rules:

  • If optionALWAYS_RETURN_LISTis present an empty list will be returned
  • If optionALWAYS_RETURN_LISTisNOTpresent null returned

JsonProvider SPI

JsonPath is shipped with three different JsonProviders:

Changing the configuration defaults as demonstrated should only be done when your application is being initialized. Changes during runtime is strongly discouraged, especially in multi threaded applications.

Configuration.setDefaults(newConfiguration.Defaults() {privatefinalJsonProviderjsonProvider=newJacksonJsonProvider();privatefinalMappingProvidermappingProvider=newJacksonMappingProvider();@OverridepublicJsonProviderjsonProvider() {returnjsonProvider;
    }@OverridepublicMappingProvidermappingProvider() {returnmappingProvider;
    }@OverridepublicSet<Option>options() {returnEnumSet.noneOf(Option.class);

Note that the JacksonJsonProvider requirescom.fasterxml.jackson.core:jackson-databind:2.4.5and the GsonJsonProvider your classpath.

Cache SPI

In JsonPath 2.1.0 a new Cache SPI was introduced. This allows API consumers to configure path caching in a way that suits their needs. The cache must be configured before it is accesses for the first time or a JsonPathException is thrown. JsonPath ships with two cache implementations

  • com.jayway.jsonpath.spi.cache.LRUCache(default, thread safe)
  • com.jayway.jsonpath.spi.cache.NOOPCache(no cache)

If you want to implement your own cache the API is simple.

CacheProvider.setCache(newCache() {//Not thread safe simple cacheprivateMap<String,JsonPath>map=newHashMap<String,JsonPath>();@OverridepublicJsonPathget(Stringkey) {returnmap.get(key);
    }@Overridepublicvoidput(Stringkey,JsonPathjsonPath) {
        map.put(key, jsonPath);


相关 [github json path] 推荐:

GitHub - json-path/JsonPath: Java JsonPath implementation json 类xpath 解析工具

- -
JsonPath expressions always refer to a JSON structure in the same way as XPath expression are used in combination with an XML document. Functions can be invoked at the tail end of a path - the input to a function is the output of the path expression.

【iShout】Path 且行且珍惜

- 个篱 - 爱范儿 · Beats of Bits
Path 是两个前 Facebook 员工的创意,被称为反社交(Anti-Social)网络应用,我们之前曾有多篇报道. faytoday 认为互联网的创新,在运气背后总有哲理,只有这样,成功才能被解释,所以他在这篇短文中从 Social 应用中的人际关系解读了 Path 的反社交理念. 如果您也有一些思考希望能够通过 iShout 这个平台来发声,请通过 iShout 与我们联系.

Path 上演“华丽”转身

- 甜菜 - 爱范儿 · Beats of Bits
还记得那款曾经拒绝了 Google 一亿美元收购报价的应用程序 Path 吗. 今年早些时候,这款由两个前 Facebook 员工精心打造出来的“密友社交平台”已经突破了 100 万的用户数量. 然而,如果你对它的印象还只是停留在“一款与 Instagram 无异的照片分享类应用程序”上的话,恐怕它这次的改变要让你刮目相看了:本周,Path 发布了 2.0 版本的重大更新——除了在用户界面设计上有了天翻地覆的改进之外,新增的一些功能也开始彰显出设计团队对于私密朋友间社交模式的新思考.

path 2.0的华丽转身

- - 用户体验与交互设计
  path2.0惊艳了很多人吧. 敢于拒绝google一亿美金的收购,果然有留一手:).   她的创始人Dave Morin说新版不久就已经超过150万人下载,而老版一年才突破了100万关口. 用户一天内在新版分享的内容超过老版一年的内容.   path2.0之后带来的用户量和活跃用户的暴增最大的功臣莫过于 界面设计和体验上的不俗表现:.


- - ITeye博客
    JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,易于阅读和编写,同时也易于机器解析和生成. 它基于ECMA262语言规范(1999-12第三版)中JavaScript编程语言的一个子集. JSON采用与编程语言无关的文本格式,但是也使用了类C语言(包括C, C++, C#, Java, JavaScript, Perl, Python等)的习惯,这些特性使JSON成为理想的数据交换格式.


- $n0wd0wn - 博客园-首页原创精华区
Json是数据交换的一种格式,与XML类似,但也有不同. 由于Json的轻便性,跨平台性和易于阅读,项目中经常用到. 所以说:Json是一种轻量级的数据交换格式. Json最简单的表现形式就键值对(key/value pairs),比如:. Json数组可以用来表示一个键key对应多个值value的情况,把这个value用{}包起来.


- - CSDN博客推荐文章
   目前,在web开发领域,主要的数据交换格式有XML和JSON,对于XML相信大家都很熟悉. XML不仅能处理数字和文字等经典的数据,还可以管理文件,格式化,图像,音频,视频,以及更多.  JSON是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成. 如今,我们经常会面临创建数据文件时,JSON和XML之间的选择.


- - CSDN博客推荐文章
        JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.  Name:Value  格式:. 一个object可以由一个或多个无序的这种组合 组成:. 2.有序的(array):. array 是 值(value) 的有序集合,格式:. array的值(alue) 可以是是双引号括起来的字符串(string)、数值(number)、 true、 false、  null、 对象(object)或者 数组(array).


- - 四火的唠叨
不久前看到一个讨论帖,说的是XML和JSON的比较,说着说着后来就变成了JSON到底比XML牛逼在哪里. 不吹不黑,客观地来比较一下二者的异同. 有的情况下是的,但也不一定,比较这样的片段:. 二者信息量几乎均等,XML看起来并不显得多么冗余. 有恰当的编辑器,二者都可以有比较美观的缩进表达. 当然,也有很多情况我们可以看到XML要比JSON啰嗦(有人说JSON是fat-free alternative to XML),比如XML写这样的东西:.


- - CSDN博客推荐文章
JSON是JavaScript Object Notation的缩写,可见JSON来源于JavaScript. JSON数据是一系列键值对的集合. JSON和JavaScript交互更加方便. JSON对数据的描述性没有XML好. JSON的速度要远远大于XML. JSON的解析要比XML的解析要方便.