{"id":13482514,"url":"https://github.com/json-path/JsonPath","last_synced_at":"2025-03-27T13:31:58.550Z","repository":{"id":1341645,"uuid":"1287669","full_name":"json-path/JsonPath","owner":"json-path","description":"Java JsonPath implementation","archived":false,"fork":false,"pushed_at":"2024-07-30T13:29:30.000Z","size":2694,"stargazers_count":8918,"open_issues_count":409,"forks_count":1645,"subscribers_count":289,"default_branch":"master","last_synced_at":"2024-10-29T15:03:32.531Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/json-path.png","metadata":{"files":{"readme":"README.md","changelog":"changelog.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2011-01-24T13:19:19.000Z","updated_at":"2024-10-29T12:29:20.000Z","dependencies_parsed_at":"2023-07-05T15:46:36.813Z","dependency_job_id":"330aa0c2-b151-49a0-90e5-cf8c0e1e94dc","html_url":"https://github.com/json-path/JsonPath","commit_stats":{"total_commits":762,"total_committers":111,"mean_commits":6.864864864864865,"dds":0.5708661417322834,"last_synced_commit":"21de6207945dfca6b49809fa9dd08c3781b7ab9d"},"previous_names":["jayway/jsonpath"],"tags_count":25,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/json-path%2FJsonPath","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/json-path%2FJsonPath/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/json-path%2FJsonPath/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/json-path%2FJsonPath/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/json-path","download_url":"https://codeload.github.com/json-path/JsonPath/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245854458,"owners_count":20683357,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T17:01:02.819Z","updated_at":"2025-03-27T13:31:58.219Z","avatar_url":"https://github.com/json-path.png","language":"Java","readme":"Jayway JsonPath\n=====================\n\n**A Java DSL for reading JSON documents.**\n\n[![Build Status](https://travis-ci.org/json-path/JsonPath.svg?branch=master)](https://travis-ci.org/json-path/JsonPath)\n[![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.jayway.jsonpath/json-path/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.jayway.jsonpath/json-path)\n[![Javadoc](https://www.javadoc.io/badge/com.jayway.jsonpath/json-path.svg)](http://www.javadoc.io/doc/com.jayway.jsonpath/json-path)\n\nJayway JsonPath is a Java port of [Stefan Goessner JsonPath implementation](http://goessner.net/articles/JsonPath/). \n\nGetting Started\n---------------\n\nJsonPath is available at the Central Maven Repository. Maven users add this to your POM.\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupId\u003ecom.jayway.jsonpath\u003c/groupId\u003e\n    \u003cartifactId\u003ejson-path\u003c/artifactId\u003e\n    \u003cversion\u003e2.9.0\u003c/version\u003e\n\u003c/dependency\u003e\n```\n\nIf you need help ask questions at [Stack Overflow](http://stackoverflow.com/questions/tagged/jsonpath). Tag the question 'jsonpath' and 'java'.\n\nJsonPath expressions always refer to a JSON structure in the same way as XPath expression are used in combination \nwith an XML document. The \"root member object\" in JsonPath is always referred to as `$` regardless if it is an \nobject or array.\n\nJsonPath expressions can use the dot–notation\n\n`$.store.book[0].title`\n\nor the bracket–notation\n\n`$['store']['book'][0]['title']`\n\nOperators\n---------\n\n| Operator                  | Description                                                        |\n| :------------------------ | :----------------------------------------------------------------- |\n| `$`                       | The root element to query. This starts all path expressions.       |\n| `@`                       | The current node being processed by a filter predicate.            |\n| `*`                       | Wildcard. Available anywhere a name or numeric are required.       |\n| `..`                      | Deep scan. Available anywhere a name is required.                  |\n| `.\u003cname\u003e`                 | Dot-notated child                                                  |\n| `['\u003cname\u003e' (, '\u003cname\u003e')]` | Bracket-notated child or children                                  |\n| `[\u003cnumber\u003e (, \u003cnumber\u003e)]` | Array index or indexes                                             |\n| `[start:end]`             | Array slice operator                                               |\n| `[?(\u003cexpression\u003e)]`       | Filter expression. Expression must evaluate to a boolean value.    |\n\n\nFunctions\n---------\n\nFunctions can be invoked at the tail end of a path - the input to a function is the output of the path expression.\nThe function output is dictated by the function itself.\n\n| Function    | Description                                                                          | Output type          |\n|:------------|:-------------------------------------------------------------------------------------|:---------------------|\n| `min()`     | Provides the min value of an array of numbers                                        | Double               |\n| `max()`     | Provides the max value of an array of numbers                                        | Double               |\n| `avg()`     | Provides the average value of an array of numbers                                    | Double               | \n| `stddev()`  | Provides the standard deviation value of an array of numbers                         | Double               | \n| `length()`  | Provides the length of an array                                                      | Integer              |\n| `sum()`     | Provides the sum value of an array of numbers                                        | Double               |\n| `keys()`    | Provides the property keys (An alternative for terminal tilde `~`)                   | `Set\u003cE\u003e`             |\n| `concat(X)` | Provides a concatinated version of the path output with a new item                   | like input           |\n| `append(X)` | add an item to the json path output array                                            | like input           |\n| `first()`   | Provides the first item of an array                                                  | Depends on the array |\n| `last()`    | Provides the last item of an array                                                   | Depends on the array |\n| `index(X)`  | Provides the item of an array of index: X, if the X is negative, take from backwards | Depends on the array |\n\nFilter Operators\n-----------------\n\nFilters are logical expressions used to filter arrays. A typical filter would be `[?(@.age \u003e 18)]` where `@` represents the current item being processed. More complex filters can be created with logical operators `\u0026\u0026` and `||`. String literals must be enclosed by single or double quotes (`[?(@.color == 'blue')]` or `[?(@.color == \"blue\")]`).   \n\n| Operator                 | Description                                                           |\n| :----------------------- | :-------------------------------------------------------------------- |\n| `==`                     | left is equal to right (note that 1 is not equal to '1')              |\n| `!=`                     | left is not equal to right                                            |\n| `\u003c`                      | left is less than right                                               |\n| `\u003c=`                     | left is less or equal to right                                        |\n| `\u003e`                      | left is greater than right                                            |\n| `\u003e=`                     | left is greater than or equal to right                                |\n| `=~`                     | left matches regular expression  [?(@.name =~ /foo.*?/i)]             |\n| `in`                     | left exists in right [?(@.size in ['S', 'M'])]                        |\n| `nin`                    | left does not exists in right                                         |\n| `subsetof`               | left is a subset of right [?(@.sizes subsetof ['S', 'M', 'L'])]       |\n| `anyof`                  | left has an intersection with right [?(@.sizes anyof ['M', 'L'])]     |\n| `noneof`                 | left has no intersection with right [?(@.sizes noneof ['M', 'L'])]    |\n| `size`                   | size of left (array or string) should match right                     |\n| `empty`                  | left (array or string) should be empty                                |\n\n\nPath Examples\n-------------\n\nGiven the json\n\n```javascript\n{\n    \"store\": {\n        \"book\": [\n            {\n                \"category\": \"reference\",\n                \"author\": \"Nigel Rees\",\n                \"title\": \"Sayings of the Century\",\n                \"price\": 8.95\n            },\n            {\n                \"category\": \"fiction\",\n                \"author\": \"Evelyn Waugh\",\n                \"title\": \"Sword of Honour\",\n                \"price\": 12.99\n            },\n            {\n                \"category\": \"fiction\",\n                \"author\": \"Herman Melville\",\n                \"title\": \"Moby Dick\",\n                \"isbn\": \"0-553-21311-3\",\n                \"price\": 8.99\n            },\n            {\n                \"category\": \"fiction\",\n                \"author\": \"J. R. R. Tolkien\",\n                \"title\": \"The Lord of the Rings\",\n                \"isbn\": \"0-395-19395-8\",\n                \"price\": 22.99\n            }\n        ],\n        \"bicycle\": {\n            \"color\": \"red\",\n            \"price\": 19.95\n        }\n    },\n    \"expensive\": 10\n}\n```\n\n| JsonPath                                       | Result |\n|:-------------------------------------------------------------------| :----- |\n| `$.store.book[*].author` | The authors of all books     |\n| `$..author`                           | All authors                         |\n| `$.store.*`                           | All things, both books and bicycles  |\n| `$.store..price`                 | The price of everything         |\n| `$..book[2]`                         | The third book                      |\n| `$..book[-2]`                       | The second to last book            |\n| `$..book[0,1]`                     | The first two books               |\n| `$..book[:2]`                       | All books from index 0 (inclusive) until index 2 (exclusive) |\n| `$..book[1:2]`                     | All books from index 1 (inclusive) until index 2 (exclusive) |\n| `$..book[-2:]`                     | Last two books                   |\n| `$..book[2:]`                     | All books from index 2 (inclusive) to last  |\n| `$..book[?(@.isbn)]`                                                 | All books with an ISBN number         |\n| `$.store.book[?(@.price \u003c 10)]`                                      | All books in store cheaper than 10  |\n| `$..book[?(@.price \u003c= $['expensive'])]`                              | All books in store that are not \"expensive\"  |\n| `$..book[?(@.author =~ /.*REES/i)]`                                  | All books matching regex (ignore case)  |\n| `$..*`                                                               | Give me every thing   \n| `$..book.length()`                                                   | The number of books                      |\n\nReading a Document\n------------------\nThe simplest most straight forward way to use JsonPath is via the static read API.\n\n```java\nString json = \"...\";\n\nList\u003cString\u003e authors = JsonPath.read(json, \"$.store.book[*].author\");\n```\n\nIf 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 \nto go since the document will be parsed every time you call JsonPath.read(...). To avoid the problem you can \nparse the json first.\n\n```java\nString json = \"...\";\nObject document = Configuration.defaultConfiguration().jsonProvider().parse(json);\n\nString author0 = JsonPath.read(document, \"$.store.book[0].author\");\nString author1 = JsonPath.read(document, \"$.store.book[1].author\");\n```\nJsonPath also provides a fluent API. This is also the most flexible one.\n\n```java\nString json = \"...\";\n\nReadContext ctx = JsonPath.parse(json);\n\nList\u003cString\u003e authorsOfBooksWithISBN = ctx.read(\"$.store.book[?(@.isbn)].author\");\n\n\nList\u003cMap\u003cString, Object\u003e\u003e expensiveBooks = JsonPath\n                            .using(configuration)\n                            .parse(json)\n                            .read(\"$.store.book[?(@.price \u003e 10)]\", List.class);\n```\n\nWhat is Returned When?\n----------------------\nWhen using JsonPath in java its important to know what type you expect in your result. JsonPath will automatically \ntry to cast the result to the type expected by the invoker.\n\n```java\n//Will throw an java.lang.ClassCastException    \nList\u003cString\u003e list = JsonPath.parse(json).read(\"$.store.book[0].author\");\n\n//Works fine\nString author = JsonPath.parse(json).read(\"$.store.book[0].author\");\n```\n\nWhen evaluating a path you need to understand the concept of when a path is `definite`. A path is `indefinite` if it contains:\n\n* `..` - a deep scan operator\n* `?(\u003cexpression\u003e)` - an expression\n* `[\u003cnumber\u003e, \u003cnumber\u003e (, \u003cnumber\u003e)]` - multiple array indexes\n\n`Indefinite` paths always returns a list (as represented by current JsonProvider). \n\nBy 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\ntry to perform the mapping. In the example below mapping between `Long` and `Date` is demonstrated. \n\n```java\nString json = \"{\\\"date_as_long\\\" : 1411455611975}\";\n\nDate date = JsonPath.parse(json).read(\"$['date_as_long']\", Date.class);\n```\n\nIf you configure JsonPath to use `JacksonMappingProvider`, `GsonMappingProvider`, or `JakartaJsonProvider` you can even map your JsonPath output directly into POJO's.\n\n```java\nBook book = JsonPath.parse(json).read(\"$.store.book[0]\", Book.class);\n```\n\nTo obtain full generics type information, use TypeRef.\n\n```java\nTypeRef\u003cList\u003cString\u003e\u003e typeRef = new TypeRef\u003cList\u003cString\u003e\u003e() {};\n\nList\u003cString\u003e titles = JsonPath.parse(JSON_DOCUMENT).read(\"$.store.book[*].title\", typeRef);\n```\n\nPredicates\n----------\nThere are three different ways to create filter predicates in JsonPath.\n\n### Inline Predicates\n\nInline predicates are the ones defined in the path.\n\n```java\nList\u003cMap\u003cString, Object\u003e\u003e books =  JsonPath.parse(json)\n                                     .read(\"$.store.book[?(@.price \u003c 10)]\");\n```\n\nYou can use `\u0026\u0026` and `||` to combine multiple predicates `[?(@.price \u003c 10 \u0026\u0026 @.category == 'fiction')]` , \n`[?(@.category == 'reference' || @.price \u003e 10)]`.\n \nYou can use `!` to negate a predicate `[?(!(@.price \u003c 10 \u0026\u0026 @.category == 'fiction'))]`.\n\n### Filter Predicates\n \nPredicates can be built using the Filter API as shown below:\n\n```java\nimport static com.jayway.jsonpath.JsonPath.parse;\nimport static com.jayway.jsonpath.Criteria.where;\nimport static com.jayway.jsonpath.Filter.filter;\n...\n...\n\nFilter cheapFictionFilter = filter(\n   where(\"category\").is(\"fiction\").and(\"price\").lte(10D)\n);\n\nList\u003cMap\u003cString, Object\u003e\u003e books =  \n   parse(json).read(\"$.store.book[?]\", cheapFictionFilter);\n\n```\nNotice 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 \nthe number of provided filters. You can specify multiple predicate placeholders in one filter operation `[?, ?]`, both predicates must match. \n\nFilters can also be combined with 'OR' and 'AND'\n```java\nFilter fooOrBar = filter(\n   where(\"foo\").exists(true)).or(where(\"bar\").exists(true)\n);\n   \nFilter fooAndBar = filter(\n   where(\"foo\").exists(true)).and(where(\"bar\").exists(true)\n);\n```\n\n### Roll Your Own\n \nThird option is to implement your own predicates\n \n```java \nPredicate booksWithISBN = new Predicate() {\n    @Override\n    public boolean apply(PredicateContext ctx) {\n        return ctx.item(Map.class).containsKey(\"isbn\");\n    }\n};\n\nList\u003cMap\u003cString, Object\u003e\u003e books = \n   reader.read(\"$.store.book[?].isbn\", List.class, booksWithISBN);\n```\n\nPath vs Value\n-------------\nIn the Goessner implementation a JsonPath can return either `Path` or `Value`. `Value` is 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 achieved with an option.\n\n```java\nConfiguration conf = Configuration.builder()\n   .options(Option.AS_PATH_LIST).build();\n\nList\u003cString\u003e pathList = using(conf).parse(json).read(\"$..author\");\n\nassertThat(pathList).containsExactly(\n    \"$['store']['book'][0]['author']\",\n    \"$['store']['book'][1]['author']\",\n    \"$['store']['book'][2]['author']\",\n    \"$['store']['book'][3]['author']\");\n```\n\nSet a value \n-----------\nThe library offers the possibility to set a value.\n\n```java\nString newJson = JsonPath.parse(json).set(\"$['store']['book'][0]['author']\", \"Paul\").jsonString();\n```\n\n\n\nTweaking Configuration\n----------------------\n\n### Options\nWhen creating your Configuration there are a few option flags that can alter the default behaviour.\n\n**DEFAULT_PATH_LEAF_TO_NULL**\n\u003cbr/\u003e\nThis option makes JsonPath return null for missing leafs. Consider the following json\n\n```javascript\n[\n   {\n      \"name\" : \"john\",\n      \"gender\" : \"male\"\n   },\n   {\n      \"name\" : \"ben\"\n   }\n]\n```\n\n```java\nConfiguration conf = Configuration.defaultConfiguration();\n\n//Works fine\nString gender0 = JsonPath.using(conf).parse(json).read(\"$[0]['gender']\");\n//PathNotFoundException thrown\nString gender1 = JsonPath.using(conf).parse(json).read(\"$[1]['gender']\");\n\nConfiguration conf2 = conf.addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL);\n\n//Works fine\nString gender0 = JsonPath.using(conf2).parse(json).read(\"$[0]['gender']\");\n//Works fine (null is returned)\nString gender1 = JsonPath.using(conf2).parse(json).read(\"$[1]['gender']\");\n```\n \n**ALWAYS_RETURN_LIST**\n\u003cbr/\u003e\nThis option configures JsonPath to return a list even when the path is `definite`. \n \n```java\nConfiguration conf = Configuration.defaultConfiguration();\n\n//ClassCastException thrown\nList\u003cString\u003e genders0 = JsonPath.using(conf).parse(json).read(\"$[0]['gender']\");\n\nConfiguration conf2 = conf.addOptions(Option.ALWAYS_RETURN_LIST);\n\n//Works fine\nList\u003cString\u003e genders0 = JsonPath.using(conf2).parse(json).read(\"$[0]['gender']\");\n``` \n**SUPPRESS_EXCEPTIONS**\n\u003cbr/\u003e\nThis option makes sure no exceptions are propagated from path evaluation. It follows these simple rules:\n\n* If option `ALWAYS_RETURN_LIST` is present an empty list will be returned\n* If option `ALWAYS_RETURN_LIST` is **NOT** present null returned \n\n**REQUIRE_PROPERTIES**\n\u003c/br\u003e\nThis option configures JsonPath to require properties defined in path when an `indefinite` path is evaluated.\n\n```java\nConfiguration conf = Configuration.defaultConfiguration();\n\n//Works fine\nList\u003cString\u003e genders = JsonPath.using(conf).parse(json).read(\"$[*]['gender']\");\n\nConfiguration conf2 = conf.addOptions(Option.REQUIRE_PROPERTIES);\n\n//PathNotFoundException thrown\nList\u003cString\u003e genders = JsonPath.using(conf2).parse(json).read(\"$[*]['gender']\");\n```\n\n### JsonProvider SPI\n\nJsonPath is shipped with five different JsonProviders:\n\n* [JsonSmartJsonProvider](https://github.com/netplex/json-smart-v2) (default)\n* [JacksonJsonProvider](https://github.com/FasterXML/jackson)\n* [JacksonJsonNodeJsonProvider](https://github.com/FasterXML/jackson)\n* [GsonJsonProvider](https://code.google.com/p/google-gson/) \n* [JsonOrgJsonProvider](https://github.com/stleary/JSON-java)\n* [JakartaJsonProvider](https://javaee.github.io/jsonp/)\n\nChanging 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.\n  \n```java\nConfiguration.setDefaults(new Configuration.Defaults() {\n\n    private final JsonProvider jsonProvider = new JacksonJsonProvider();\n    private final MappingProvider mappingProvider = new JacksonMappingProvider();\n      \n    @Override\n    public JsonProvider jsonProvider() {\n        return jsonProvider;\n    }\n\n    @Override\n    public MappingProvider mappingProvider() {\n        return mappingProvider;\n    }\n    \n    @Override\n    public Set\u003cOption\u003e options() {\n        return EnumSet.noneOf(Option.class);\n    }\n});\n```\n\nNote that the JacksonJsonProvider requires `com.fasterxml.jackson.core:jackson-databind:2.4.5` and the GsonJsonProvider requires `com.google.code.gson:gson:2.3.1` on your classpath. \n\nBoth of Jakarta EE 9 [JSON-P (JSR-342)](https://javaee.github.io/jsonp/) and [JSON-B (JSR-367)](http://json-b.net/) providers expect at least Java 8 and require compatible JSON API implementations (such as [Eclipse Glassfish](https://projects.eclipse.org/projects/ee4j.jsonp) and [Eclipse Yasson](https://projects.eclipse.org/projects/ee4j.yasson)) on application runtime classpath; such implementations may also be provided by Java EE application container. Please also note that Apache Johnzon is not classpath-compatible with Jakarta EE 9 specification yet, and if JSON-B mapping provider is chosen then JSON-P provider must be configured and used, too.\n\nOne peculiarity of Jakarta EE 9 specifications for JSON processing and databinding (mapping) is immutability of Json arrays and objects as soon as they are fully parsed or written to. To respect the API specification, but allow JsonPath to modify Json documents through add, set/put, replace, and delete operations, `JakartaJsonProvider` has to be initiliazed with optional `true` argument:\n\n* `JsonProvider jsonProvider = new JakartaJsonProvider(true)` (enable mutable Json arrays and objects)\n* `JsonProvider jsonProvider = new JakartaJsonProvider()` (default, strict JSON-P API compliance)\n\nAll lookup and read operations with JsonPath are supported regardless of initilization mode. Default mode also needs less memory and is more performant.\n  \n\n### Cache SPI\n\nIn 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\n\n* `com.jayway.jsonpath.spi.cache.LRUCache` (default, thread safe)\n* `com.jayway.jsonpath.spi.cache.NOOPCache` (no cache)\n\nIf you want to implement your own cache the API is simple. \n\n```java\nCacheProvider.setCache(new Cache() {\n    //Not thread safe simple cache\n    private Map\u003cString, JsonPath\u003e map = new HashMap\u003cString, JsonPath\u003e();\n\n    @Override\n    public JsonPath get(String key) {\n        return map.get(key);\n    }\n\n    @Override\n    public void put(String key, JsonPath jsonPath) {\n        map.put(key, jsonPath);\n    }\n});\n```\n\n\n\n\n\n\n[![Analytics](https://ga-beacon.appspot.com/UA-54945131-1/jsonpath/index)](https://github.com/igrigorik/ga-beacon)\n","funding_links":[],"categories":["Java","HarmonyOS","Java程序设计","项目","Projects","Technologies we used in the Microservices","\u003ca name=\"Java\"\u003e\u003c/a\u003eJava"],"sub_categories":["Windows Manager","资源传输下载","JSON","Networking"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjson-path%2FJsonPath","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjson-path%2FJsonPath","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjson-path%2FJsonPath/lists"}