Jayway JsonPath Documentation

repository·master·Indexed 27 days ago

https://github.com/json-path/jsonpath

A Java DSL for reading and querying JSON documents using a syntax similar to XPath. It provides operators, functions, and filtering capabilities to navigate complex JSON structures. The library includes a static API for one-off reads, a ReadContext for efficient multiple queries, and the json-path-assert module for Hamcrest matchers to perform JSON assertions.

Tokens
3.1K
Snippets
13
Records
15
Agent score
44%

What's inside Jayway JsonPath

  1. Use JsonPath matchers for assertions

    master

    To use the library, statically import com.jayway.jsonpath.matchers.JsonPathMatchers.*. The matchers work with Strings, Files, or already parsed JSON objects. Note that the evaluation depends on your current Configuration settings.

    import static com.jayway.jsonpath.matchers.JsonPathMatchers.*;
    
    // Supported JSON representations:
    String json = ...;
    File json = ...;
    Object json = Configuration.defaultConfiguration().jsonProvider().parse(content);
    
    // Basic assertions
    assertThat(json, isJson());
    assertThat(json, hasJsonPath("$.message"));
    assertThat(json, hasNoJsonPath("$.message"));
    
    // Value assertions
    assertThat(json, hasJsonPath("$.message", equalTo("Hi there")));
    assertThat(json, hasJsonPath("$.quantity", equalTo(5)));
    assertThat(json, hasJsonPath("$.store.book[*].author", hasSize(4)));
    assertThat(json, hasJsonPath("$.store.book[*].author", hasItem("Evelyn Waugh")));
  2. Create filter predicates

    master

    There are three ways to create filters:

    1. Inline Predicates: Defined directly in the path string using [?(<expression>)].
    2. Filter Predicates: Built using the Criteria and Filter API.
    3. Custom Predicates: Implementing the Predicate interface.
    // 1. Inline
    List<Map<String, Object>> books = JsonPath.parse(json).read("$.store.book[?(@.price < 10)]");
    
    // 2. Filter API
    import static com.jayway.jsonpath.JsonPath.parse;
    import static com.jayway.jsonpath.Criteria.where;
    import static com.jayway.jsonpath.Filter.filter;
    
    Filter cheapFictionFilter = filter(
            where("category").is("fiction").and("price").lte(10D)
    );
    List<Map<String, Object>> books = parse(json).read("$.store.book[?]", cheapFictionFilter);
    
    // 3. Custom Predicate
    Predicate booksWithISBN = new Predicate() {
        @Override
        public boolean apply(PredicateContext ctx) {
            return ctx.item(Map.class).containsKey("isbn");
        }
    };
    List<Map<String, Object>> books = reader.read("$.store.book[?].isbn", List.class, booksWithISBN);
  3. Read JSON documents efficiently using ReadContext

    master

    To avoid re-parsing the JSON document when performing multiple queries, parse the document once into an Object or use the fluent JsonPath.parse() API to obtain a ReadContext.

    String json = "...";
    
    // Option 1: Parse once to an Object
    Object document = Configuration.defaultConfiguration().jsonProvider().parse(json);
    String author0 = JsonPath.read(document, "$.store.book[0].author");
    String author1 = JsonPath.read(document, "$.store.book[1].author");
    
    // Option 2: Use the fluent API (ReadContext)
    ReadContext ctx = JsonPath.parse(json);
    List<String> authorsOfBooksWithISBN = ctx.read("$.store.book[?(@.isbn)].author");
  4. Install Jayway JsonPath via Maven

    master

    Add the following dependency to your pom.xml to use JsonPath in your Maven project. Note that version 3.0.0 uses a Java 17 baseline to support Jackson 3.

    <dependency>
        <groupId>com.jayway.jsonpath</groupId>
        <artifactId>json-path</artifactId>
        <version>3.0.0</version>
    </dependency>
  5. Configure JsonPath Options

    master

    Use Configuration.addOptions() to change default behaviors:

    • Option.DEFAULT_PATH_LEAF_TO_NULL: Returns null for missing leaves instead of throwing an exception.
    • Option.ALWAYS_RETURN_LIST: Ensures the result is always a List, even for definite paths.
    • Option.SUPPRESS_EXCEPTIONS: Prevents exceptions from propagating (returns empty list or null depending on ALWAYS_RETURN_LIST).
    • Option.REQUIRE_PROPERTIES: Requires properties defined in the path to exist during indefinite scans.
  6. Configure JsonPath Providers (JsonProvider and MappingProvider)

    master

    You can customize the underlying JSON engine and mapping logic by setting global defaults. This should be done during application initialization.

    Configuration.setDefaults(new Configuration.Defaults() {
        private final JsonProvider jsonProvider = new JacksonJsonProvider();
        private final MappingProvider mappingProvider = new JacksonMappingProvider();
    
        @Override
        public JsonProvider jsonProvider () {
            return jsonProvider;
        }
    
        @Override
        public MappingProvider mappingProvider () {
            return mappingProvider;
        }
    
        @Override
        public Set<Option> options () {
            return EnumSet.noneOf(Option.class);
        }
    });
  7. Match on pre-compiled complex JsonPath expressions

    master

    You can use filter() to create complex predicates and then compile them into a JsonPath object to use with withJsonPath().

    Filter cheapFictionFilter = filter(
        where("category").is("fiction").and("price").lte(10D));
    JsonPath cheapFiction = JsonPath.compile("$.store.book[?]", cheapFictionFilter);
    String json = ...;
    assertThat(json, isJson(withJsonPath(cheapFiction)));
  8. Combine JsonPath matchers

    master

    You can combine matchers to separate JSON parsing from path evaluation or to perform multiple evaluations in a single statement (which parses the JSON only once).

    // Separate parsing from path evaluation
    assertThat(json, isJson(withoutJsonPath("...")));
    assertThat(json, isJson(withJsonPath("...", equalTo(3))));
    
    // Combine several evaluations into one statement
    assertThat(json, isJson(allOf(
        withJsonPath("$.store.name", equalTo("Little Shop")),
        withoutJsonPath("$.expensive"),
        withJsonPath("$..title", hasSize(4))
    )));
  9. Implement a custom Cache provider

    master

    Since version 2.1.0, you can implement the Cache interface to control how paths are cached. The cache must be configured before it is accessed for the first time.

    CacheProvider.setCache(new Cache() {
        private Map<String, JsonPath> map = new HashMap<String, JsonPath>();
    
        @Override
        public JsonPath get (String key){
            return map.get(key);
        }
    
        @Override
        public void put (String key, JsonPath jsonPath){
            map.put(key, jsonPath);
        }
    });
  10. Use typed matchers for specific JSON representations

    master

    If you need to assert the type of the input JSON, use isJsonString or isJsonFile in conjunction with withJsonPath.

    String json = ...;
    assertThat(json, isJsonString(withJsonPath("$..author")));
    
    File json = ...;
    assertThat(json, isJsonFile(withJsonPath("$..author")));
  11. Read JSON documents using the static API

    master

    The simplest way to use JsonPath is via the JsonPath.read() static method. This is suitable for one-off reads, but note that the document is parsed every time this method is called.

    String json = "...";
    
    List<String> authors = JsonPath.read(json, "$.store.book[*].author");