Java JsonPath implementation

Related tags

JSON JsonPath
Overview

Jayway JsonPath

A Java DSL for reading JSON documents.

Build Status Maven Central Javadoc

Jayway JsonPath is a Java port of Stefan Goessner JsonPath implementation.

News

10 Dec 2020 - Released JsonPath 2.5.0

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.

<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.5.0</version>
</dependency>

If you need help ask questions at Stack 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

$.store.book[0].title

or the bracket–notation

$['store']['book'][0]['title']

Operators

Operator Description
$ 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

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.

Function Description Output
min() Provides the min value of an array of numbers Double
max() Provides the max value of an array of numbers Double
avg() Provides the average value of an array of numbers Double
stddev() Provides the standard deviation value of an array of numbers Double
length() Provides the length of an array Integer
sum() Provides the sum value of an array of numbers Double
keys() Provides the property keys (An alternative for terminal tilde ~) Set<E>

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")]).

Operator Description
== 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 [?(@.name =~ /foo.*?/i)]
in left exists in right [?(@.size in ['S', 'M'])]
nin left does not exists in right
subsetof left is a subset of right [?(@.sizes subsetof ['S', 'M', 'L'])]
anyof left has an intersection with right [?(@.sizes anyof ['M', 'L'])]
noneof left has no intersection with right [?(@.sizes noneof ['M', 'L'])]
size size of left (array or string) should match right
empty left (array or string) should be empty

Path Examples

Given the json

{
    "store": {
        "book": [
            {
                "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
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
    "expensive": 10
}
JsonPath (click link to try) Result
$.store.book[*].author The authors of all books
$..author All authors
$.store.* All things, both books and bicycles
$.store..price The price of everything
$..book[2] The third book
$..book[-2] The second to last book
$..book[0,1] The first two books
$..book[:2] All books from index 0 (inclusive) until index 2 (exclusive)
$..book[1:2] All books from index 1 (inclusive) until index 2 (exclusive)
$..book[-2:] Last two books
$..book[2:] Book number two from tail
$..book[?(@.isbn)] All books with an ISBN number
$.store.book[?(@.price < 10)] All books in store cheaper than 10
$..book[?(@.price <= $['expensive'])] All books in store that are not "expensive"
$..book[?(@.author =~ /.*REES/i)] All books matching regex (ignore case)
$..* Give me every thing
$..book.length() The number of books

Reading a Document

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

String json = "...";

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

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 JsonPath.read(...). To avoid the problem you can parse the json first.

String json = "...";
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");

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

String json = "...";

ReadContext ctx = JsonPath.parse(json);

List<String> authorsOfBooksWithISBN = ctx.read("$.store.book[?(@.isbn)].author");


List<Map<String, Object>> expensiveBooks = JsonPath
                            .using(configuration)
                            .parse(json)
                            .read("$.store.book[?(@.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.ClassCastException    
List<String> list = JsonPath.parse(json).read("$.store.book[0].author")

//Works fine
String author = JsonPath.parse(json).read("$.store.book[0].author")

When evaluating a path you need to understand the concept of when a path is definite. A path is indefinite if it contains:

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

Indefinite paths 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 between Long and Date is demonstrated.

String json = "{\"date_as_long\" : 1411455611975}";

Date date = JsonPath.parse(json).read("$['date_as_long']", Date.class);

If you configure JsonPath to use JacksonMappingProvider or GsonMappingProvider you can even map your JsonPath output directly into POJO's.

Book book = JsonPath.parse(json).read("$.store.book[0]", Book.class);

To obtain full generics type information, use TypeRef.

TypeRef<List<String>> typeRef = new TypeRef<List<String>>() {};

List<String> titles = JsonPath.parse(JSON_DOCUMENT).read("$.store.book[*].title", typeRef);

Predicates

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

Inline Predicates

Inline predicates are the ones defined in the path.

List<Map<String, Object>> books =  JsonPath.parse(json)
                                     .read("$.store.book[?(@.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 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);

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'

Filter fooOrBar = filter(
   where("foo").exists(true)).or(where("bar").exists(true)
);
   
Filter fooAndBar = filter(
   where("foo").exists(true)).and(where("bar").exists(true)
);

Roll Your Own

Third option is to implement your own predicates

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);

Path vs Value

In 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.

Configuration conf = Configuration.builder()
   .options(Option.AS_PATH_LIST).build();

List<String> pathList = using(conf).parse(json).read("$..author");

assertThat(pathList).containsExactly(
    "$['store']['book'][0]['author']",
    "$['store']['book'][1]['author']",
    "$['store']['book'][2]['author']",
    "$['store']['book'][3]['author']");

Set a value

The library offers the possibility to set a value.

String newJson = JsonPath.parse(json).set("$['store']['book'][0]['author']", "Paul").jsonString();

Tweaking Configuration

Options

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

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

[
   {
      "name" : "john",
      "gender" : "male"
   },
   {
      "name" : "ben"
   }
]
Configuration conf = Configuration.defaultConfiguration();

//Works fine
String gender0 = JsonPath.using(conf).parse(json).read("$[0]['gender']");
//PathNotFoundException thrown
String gender1 = JsonPath.using(conf).parse(json).read("$[1]['gender']");

Configuration conf2 = conf.addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL);

//Works fine
String gender0 = JsonPath.using(conf2).parse(json).read("$[0]['gender']");
//Works fine (null is returned)
String gender1 = JsonPath.using(conf2).parse(json).read("$[1]['gender']");

ALWAYS_RETURN_LIST
This option configures JsonPath to return a list even when the path is definite.

Configuration conf = Configuration.defaultConfiguration();

//ClassCastException thrown
List<String> genders0 = JsonPath.using(conf).parse(json).read("$[0]['gender']");

Configuration conf2 = conf.addOptions(Option.ALWAYS_RETURN_LIST);

//Works fine
List<String> genders0 = JsonPath.using(conf2).parse(json).read("$[0]['gender']");

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

  • If option ALWAYS_RETURN_LIST is present an empty list will be returned
  • If option ALWAYS_RETURN_LIST is NOT present null returned

REQUIRE_PROPERTIES
This option configures JsonPath to require properties defined in path when an indefinite path is evaluated.

Configuration conf = Configuration.defaultConfiguration();

//Works fine
List<String> genders = JsonPath.using(conf).parse(json).read("$[*]['gender']");

Configuration conf2 = conf.addOptions(Option.REQUIRE_PROPERTIES);

//PathNotFoundException thrown
List<String> genders = JsonPath.using(conf2).parse(json).read("$[*]['gender']");

JsonProvider SPI

JsonPath is shipped with five 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(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);
    }
});

Note 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.

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(new Cache() {
    //Not thread safe simple 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);
    }
});

Analytics

Comments
  • JacksonJsonNodeJsonProvider disallows POJOs

    JacksonJsonNodeJsonProvider disallows POJOs

    In 2.2.0 the provider allowed Jackson POJOs to be used as values when setting a property. This is an useful feature that I very frequently. This is also a breaking change that was not documented.

    In my case the entire application is built around json schema and metadata. The schemas have triggers associated to them so that when an entity written it is inspected, a processing pipeline constructed, and operated upon. JsonPath is used at each of these stages to read and write to the entity before it is finally stored in the database, etc. The JsonNode provider is used to force all writes to normalize back into a consistent format. At least previously the JacksonJsonProvider would retain the type of the written value that could cause surprises on the next read (e.g. insert a UUID, cast exception if reading back as a String).

    As of 2.3.0, using an unknown object results in an exception. It would be helpful if this restriction was reverted.

    opened by ben-manes 21
  • Can't be used in hive-0.11: java.lang.NoClassDefFoundError

    Can't be used in hive-0.11: java.lang.NoClassDefFoundError

    The pom.xml was set according to your DOC: Getting Started.

    I run it in my laptop, it works well. However, when run it on hive 0.11, error occurred:

    Caused by: java.lang.NoClassDefFoundError: net/minidev/json/writer/JsonReaderI at com.jayway.jsonpath.internal.DefaultsImpl.(DefaultsImpl.java:17) at com.jayway.jsonpath.internal.DefaultsImpl.(DefaultsImpl.java:15) at com.jayway.jsonpath.Configuration.getEffectiveDefaults(Configuration.java:53) at com.jayway.jsonpath.Configuration.defaultConfiguration(Configuration.java:178) at com.jayway.jsonpath.internal.JsonReader.(JsonReader.java:48) at com.jayway.jsonpath.JsonPath.read(JsonPath.java:461) at com.qunar.hive.udf.ParseJsonWithPath.evaluate(ParseJsonWithPath.java:64) ... 26 more Caused by: java.lang.ClassNotFoundException: net.minidev.json.writer.JsonReaderI at java.net.URLClassLoader$1.run(URLClassLoader.java:366) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:425) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:358) ... 33 more

    Could anybody help me? Thanks a lot.

    QUESTION 
    opened by ericxsun 15
  • RenameKey funcionality

    RenameKey funcionality

    Added renameKey feature to rename a key value found in a map path to a new key value. This gratly increases the usability of the library. Unit tests were also extended to cover the new feature.

    opened by atomcat1978 14
  • memory leak

    memory leak

    One of our QA servers ran out of memory, looks like there is a memory leak in Cache.java. A simple single-threaded program to reproduce the issue is below. I think it is better to allow the user to disable the cache, and let the user create (and cache) CompiledPath instances.

    public static void main(String[] arg) {
        Cache cache = new Cache(200);
        Path dummy = new CompiledPath(null, false);
        for (int i = 0; i < 10000; ++i) {
           String key = String.valueOf(i);
           cache.get(key);
           cache.put(key, dummy);
        }
        System.out.println("cache size: " + cache.size());
    }
    
    BUG 
    opened by tranwarpxl 13
  • Incorrect comparison

    Incorrect comparison

    I have the following json,

    {"store":{"book":[{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":8},{"category":"fiction","author":"Evelyn Waugh","title":"Sword of Honour","price":12},{"category":"fiction","author":"Herman Melville","title":"Moby Dick","isbn":"0-553-21311-3","price":8},{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22}],"bicycle":{"color":"red","price":19}},"ExDataList":[{"key":"numOfPages","value":"2341","timestamp":"08-13-2015 06:32:13"},{"key":"numOfImages","value":"69","timestamp":"08-13-2015 06:32:13"},{"key":"numOfComments","value":"89","timestamp":"08-13-2015 06:32:13"},{"key":"numOfBookmarks","value":"3","timestamp":"08-13-2015 06:32:13"}],"expensive":10}

    On the above json, i am trying to evaluate the following jsonpath expression,

    $.ExDataList[?(@.key=='numOfImages' && @.value>100)]

    Ideally the above expression should return an empty arraylist, however it is returning the following,

    [{"key":"numOfImages","value":"69","timestamp":"08-13-2015 06:32:13"}]

    But if, i replace the "100" in the jsonexpression with any other value, say 98, then it is returning the correct output.

    I am using the latest release of Jayway JsonPath .

    FEATURE 
    opened by mathursharp 11
  • Support for Functions in Predicates and Json Paths

    Support for Functions in Predicates and Json Paths

    Implementation of math and array length support in predicates and paths. Initial implementation - uses Function interface as a pattern for writing new functions in the future.

    Ready for review - code coverage should be fairly high given all use-cases are supported via functional tests.

    opened by mgreenwood1001 11
  • Performance bottlenecks

    Performance bottlenecks

    I am observing high cpu usage due to extensive usage of JsonPath. Using Java Flight Recording to profile a production machine, these areas standout in JProfiler as cpu hotspots.

    1. JsonPath.getPath() This method recursively evaluates the PathToken to build the string representation. In one case we have this in a TreeSet to sort the order of evaluations, and the comparator is surprisingly expensive. Since the JsonPath is compiled and cached, it would make sense for the string representation to be lazily cached (ala String's hashCode). It may also be faster to replace recursive descent with a loop.

    2. JsonContext.pathFromCache(path) This method very inefficiently computes the cache key, resulting in excessive cpu and allocations.

      • When there are no filters, then the path can be used directly as the key.
      • Because the filters is a second arg, "[]", the concat slow path is used.
      • There is no reason to wrap a list with a LinkedList, as they have the same toString implementation.
      • Arrays.toString would be a more efficient conversion.
      • The operation could use a computeIfAbsent to avoid redundant work on a cache miss due to races.
    3. JsonPath.compile(path) This user-facing method creates a new JsonPath instead of using the cache. Therefore if one tries to optimize to bypass the slow pathFromCache call, there is high overhead. The compilation should return the cached copy, allowing the application user to benefit from the configured cache.

    4. JsonPath.read(Object, Configuration) This method uses exceptions as ordinary control flow. That is a bad practice because it is slow when many exceptions are created, as filling the stack trace is a costly operation. The internals should return a result object which could be evaluated to the suppressed value.

    opened by ben-manes 10
  • JsonPath.read() ignores REQUIRE_PROPERTIES config option when AS_PATH_LIST is set

    JsonPath.read() ignores REQUIRE_PROPERTIES config option when AS_PATH_LIST is set

    Description When I specify this (Note: REQUIRE_PROPERTIES is NOT set): Configuration jsonCfg = Configuration.builder().options( Option.AS_PATH_LIST ).build();

    And do this:

    String jsonStr = "{ \"foo\": { \"bar\" : \"val\" }, \"moo\": { \"cow\" : \"val\" } }";
    Predicate[] predicates = {};
    DocumentContext dCtx = JsonPath.using( jsonCfg ).parse( jsonStr );
    readPaths = dCtx.read( JsonPath.compile( "$.*.bar", predicates ) );
    

    Actual Behaviour I get this:

    Exception in thread "main" com.jayway.jsonpath.PathNotFoundException: No results for path: $['moo']['bar']
        at com.jayway.jsonpath.internal.token.PathToken.handleObjectProperty(PathToken.java:53)
        at com.jayway.jsonpath.internal.token.PropertyPathToken.evaluate(PropertyPathToken.java:44)
        at com.jayway.jsonpath.internal.token.PathToken.handleObjectProperty(PathToken.java:71)
        at com.jayway.jsonpath.internal.token.WildcardPathToken.evaluate(WildcardPathToken.java:32)
        at com.jayway.jsonpath.internal.token.RootPathToken.evaluate(RootPathToken.java:53)
        at com.jayway.jsonpath.internal.CompiledPath.evaluate(CompiledPath.java:53)
        at com.jayway.jsonpath.internal.CompiledPath.evaluate(CompiledPath.java:61)
        at com.jayway.jsonpath.JsonPath.read(JsonPath.java:176)
        at com.jayway.jsonpath.internal.JsonReader.read(JsonReader.java:146)
    

    Expected Behaviour I expected a List result containing a single path: $[foo].[bar] because I did not have the REQUIRE_PROPERTIES option set. I would only expect to see PathNotFoundException if REQUIRE_PROPERTIES was set.

    opened by bradleymorris 9
  • JSON Smart Security Vulnerability

    JSON Smart Security Vulnerability

    JSON Smart has not been updated in a long time and has a security vulnerability associated with it: https://nvd.nist.gov/vuln/detail/CVE-2021-27568

    Please allow us to exclude JSON Smart and use a different provider.

    opened by bperino 8
  • Issue #191 fixes both $..allTheThings.max() and $.max($..allTheThings)

    Issue #191 fixes both $..allTheThings.max() and $.max($..allTheThings)

    Issue #191 is an unintentional side-effect of the collection processing for parameters passed to functions. This change supports result set functions via patterns such as:

    $.max($..allTheNumberThings)

    $.max($.foo, $.bar) is already supported where foo and bar are numbers - consequently

    $.max($..allTheNumberThings) shall also work also

    $.avg($..allTheNumberThings, $.someCollection.max(), $..someOtherNumberThings) will work too now with this change.

    opened by mgreenwood1001 8
  • Error: duplicate entry, AnnotationVisitor.class

    Error: duplicate entry, AnnotationVisitor.class

    Hi Team,

    I know this question was issued here: https://github.com/jayway/JsonPath/issues/213 but I haven't found a solution yet.

    I would appreciate your support on this issue. I'll bet I'm not the only one with this.

    My understanding is that I am trying to package the same class twice or there are duplicate references to the same API (Likely different version numbers), I am not sure at all.

    At first time, I want to know what's the escential of this kind of problems " java.util.zip.ZipException". And second, I looking for help on how to use this library.

    @kallestenflo said: "This is a json-smart issue https://github.com/netplex/json-smart-v2. Try configuring JsonPath to use an other JsonProvider. This must be done before you access JsonPath the first time."

    How can I do this?, developing for android I am an amateur. I undertand a lot of things but in this case my mind is blowing.

    Please, tell me there is a solution for this. T.T

    Thanks in advance

    opened by denebchorny 8
  • Deep scan with length function modifies document context

    Deep scan with length function modifies document context

    Reading twice from a DocumentContext should not modify its state, but that seems to be the case since 2.6.0.

    Input:

    {
      "a": "a",
      "b": "b",
      "c": "c",
      "d": {
        "e": [
          {
            "f": "f",
            "g": "g"
          }
        ]
      }
    }
    

    Test:

        @Test
        void deepScan() {
            String json = "{"
                + "  \"a\": \"a\","
                + "  \"b\": \"b\","
                + "  \"c\": \"c\","
                + "  \"d\": {"
                + "    \"e\": ["
                + "      {"
                + "        \"f\": \"f\","
                + "        \"g\": \"g\""
                + "      }"
                + "    ]"
                + "  }"
                + "}";
            final Configuration configuration = Configuration.defaultConfiguration();
            DocumentContext jsonDocument = JsonPath.using(configuration).parse(json);
            final Object result = jsonDocument.read("$..e.length()");
            final Object result2 = jsonDocument.read("$..e.length()");
            System.out.println(result);
            System.out.println(result2);
            // assertions ommited for issue
        }
    

    Output: json-path 2.3.0 & 2.4.0: [1] [1]

    json-path 2.5.0: 4 4

    json-path 2.6.0 & 2.7.0: 1 2

    json-path 2.5.0 seems to be broken, as it counts the elements a,b,c and d. json-path >= 2.6.0 fixed that, I guess.

    However, with json-path 2.6.0 & 2.7.0 the second call to DocumentContext#read counts f and g (if the element g is removed, the result is 1 as expected).

    opened by saimonsez 0
  • Cannot set to root element

    Cannot set to root element

    Hi there,

    I am trying to use the set() function to update the root element of a JSON but I keep getting an InvalidModificationException. Here is an example in case you want to reproduce the error:

    If I try to update the complete root object, the error occurs:

    String json= "{\"name\":\"Not Peter\"}";
    String path = "$";
    String updatedJson = "{\"name\": \"Peter\"}";
    String newJson = JsonPath.parse(json).set(path, updatedJson).jsonString();
    // --> Throws com.jayway.jsonpath.InvalidModificationException: Invalid set operation
    

    I tried this with different root elements (e.g. an empty array or an empty object), but that doesn't seem to make a difference.

    When I just try to change the name property, it works:

    String json= "{\"name\":\"Not Peter\"}";
    String path = "$.name";
    String updatedJson = "Peter";
    String newJson = JsonPath.parse(json).set(path, updatedJson).jsonString();
    // -> Returns {"name":"Peter"}
    

    Am I doing something wrong? Is this expected behavior? Or is this a bug?

    opened by aljoshakoecher 0
  • Reading json from domain objects added to documentContext

    Reading json from domain objects added to documentContext

    Using jsonPath 2.7.0

    I am able to perform a documentContext add. Adding a domain object.

    When the jsonString is returned then all the domain objects are processed successfully and I get valid json.

    If though I use documentContext.read then I get the following exception com.jayway.jsonpath.PathNotFoundException: Expected to find an object with property ['domainField'] in path $['list'][0] but found 'MyDomainObject'. This is not a json object according to the JsonProvider: 'com.jayway.jsonpath.spi.json.JacksonJsonProvider'.

    When we add a domain object should it delegate to the provider/mapper to turn the domain object in to the correct type for this provider? This would make it transparent to the consumer based on what provider/mapper was chosen.

    If I changed the provider to JacksonJsonNodeJsonProvider then the below would work.

    See the below example.

            //given
            ObjectMapper MAPPER = new ObjectMapper()
                    .setNodeFactory(JsonNodeFactory.withExactBigDecimals(true))
                    .setSerializationInclusion(JsonInclude.Include.NON_NULL);
            ParseContext JSON_PARSER =
                    JsonPath.using(Configuration.builder()
                            .mappingProvider(new JacksonMappingProvider(MAPPER))
                            .jsonProvider(new JacksonJsonProvider(MAPPER))
                            .options(Option.DEFAULT_PATH_LEAF_TO_NULL)
                            .build());
    
            Map<String, ?> json = Map.of("field", "value", "list", new ArrayList<Map<String, ?>>());
            DocumentContext documentContext = JSON_PARSER.parse(json);
    
            //when
            MyDomainObject domainObject = new MyDomainObject();
            domainObject.setDomainField(10);
            documentContext.add("$.list", domainObject);
    
            //then
            assertThatJson(documentContext.jsonString()).inPath("$.list[0].domainField").isEqualTo(10);
    
            // this throws com.jayway.jsonpath.PathNotFoundException: Expected to find an object with property ['domainField'] in path $['list'][0] but found 'MyDomainObject'.
            // This is not a json object according to the JsonProvider: 'com.jayway.jsonpath.spi.json.JacksonJsonProvider'.
            assertThat(documentContext.<Integer>read("$.list[0].domainField")).isEqualTo(10);
    
    
    
    opened by andy-c21 0
  • Quickly test JSONPath

    Quickly test JSONPath

    There used to be a JSONPath online test web application where you could set to use this library.

    https://jsonpath.herokuapp.com/

    But it is down since a while. Is there anything similar to quickly test a JSONPath with that library here?

    opened by pandoras-toolbox 0
  • I get error that is Function with name: first does not exist.

    I get error that is Function with name: first does not exist.

    my code

            ReadContext rct = JsonPath.parse(JsonUtil.getJsonByFileUtils(rateJsonFilePath));
            Object data = rct.read("$.data.items");
            log.info("data:{}", data);
            Object first = rct.read("$.data.items.first()");
            log.info("first:{}", first);
    

    print

    02:08:58.437 [main] DEBUG com.jayway.jsonpath.internal.path.CompiledPath - Evaluating path: $['data']['items']
    02:08:58.437 [main] INFO com.example.demo.jsontest.JsonTest - data:[{"id":1,"app_local":"ff","tax_rate":10,"basic_rate":15.5,"expected_profit_rate":10,"update_user":"yyyyyy","update_time":1669819482},{"id":1,"app_local":"rr","tax_rate":10,"basic_rate":15.5,"expected_profit_rate":10,"update_user":"wxxxxxx","update_time":1669819482}]
    02:08:58.437 [main] DEBUG com.jayway.jsonpath.internal.path.CompiledPath - Evaluating path: $['data']['items'].first()
    Exception in thread "main" java.lang.reflect.InvocationTargetException
    	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    	at java.lang.reflect.Method.invoke(Method.java:498)
    	at com.intellij.rt.execution.CommandLineWrapper.main(CommandLineWrapper.java:64)
    Caused by: com.jayway.jsonpath.InvalidPathException: Function with name: first does not exist.
    	at com.jayway.jsonpath.internal.function.PathFunctionFactory.newFunction(PathFunctionFactory.java:71)
    	at com.jayway.jsonpath.internal.path.FunctionPathToken.evaluate(FunctionPathToken.java:38)
    	at com.jayway.jsonpath.internal.path.PathToken.handleObjectProperty(PathToken.java:90)
    	at com.jayway.jsonpath.internal.path.PropertyPathToken.evaluate(PropertyPathToken.java:80)
    	at com.jayway.jsonpath.internal.path.PathToken.handleObjectProperty(PathToken.java:90)
    	at com.jayway.jsonpath.internal.path.PropertyPathToken.evaluate(PropertyPathToken.java:80)
    	at com.jayway.jsonpath.internal.path.RootPathToken.evaluate(RootPathToken.java:66)
    	at com.jayway.jsonpath.internal.path.CompiledPath.evaluate(CompiledPath.java:99)
    	at com.jayway.jsonpath.internal.path.CompiledPath.evaluate(CompiledPath.java:107)
    	at com.jayway.jsonpath.JsonPath.read(JsonPath.java:179)
    	at com.jayway.jsonpath.internal.JsonContext.read(JsonContext.java:88)
    	at com.jayway.jsonpath.internal.JsonContext.read(JsonContext.java:77)
    	at com.example.demo.jsontest.JsonTest.main(JsonTest.java:58)
    	... 5 more
    

    the data is:

    [
          {
            "id": 1,
            "app_local": "ff",
            "tax_rate": 10,
            "basic_rate": 15.5,
            "expected_profit_rate": 10,
            "update_user": "yyyyyy",
            "update_time": 1669819482
          },
          {
            "id": 1,
            "app_local": "rr",
            "tax_rate": 10,
            "basic_rate": 15.5,
            "expected_profit_rate": 10,
            "update_user": "wxxxxxx",
            "update_time": 1669819482
          }
        ]
    
    opened by lush-99 0
Owner
null
A streaming JsonPath processor in Java

JsonSurfer - Let's surf on Json! Why JsonSurfer Streaming No need to deserialize entire json into memory. JsonPath Selectively extract json data by th

null 256 Dec 12, 2022
A reference implementation of a JSON package in Java.

JSON in Java [package org.json] Click here if you just want the latest release jar file. Overview JSON is a light-weight language-independent data int

Sean Leary 4.2k Jan 6, 2023
A JSON Schema validation implementation in pure Java, which aims for correctness and performance, in that order

Read me first The current version of this project is licensed under both LGPLv3 (or later) and ASL 2.0. The old version (2.0.x) was licensed under LGP

Java Json Tools 1.5k Jan 4, 2023
JSON-LD implementation for Java

JSONLD-Java is looking for a maintainer JSONLD-JAVA This is a Java implementation of the JSON-LD 1.0 specification and the JSON-LD-API 1.0 specificati

null 362 Dec 3, 2022
Convert Java to JSON. Convert JSON to Java. Pretty print JSON. Java JSON serializer.

json-io Perfect Java serialization to and from JSON format (available on Maven Central). To include in your project: <dependency> <groupId>com.cedar

John DeRegnaucourt 303 Dec 30, 2022
A Java serialization/deserialization library to convert Java Objects into JSON and back

Gson Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to a

Google 21.7k Jan 8, 2023
A universal types-preserving Java serialization library that can convert arbitrary Java Objects into JSON and back

A universal types-preserving Java serialization library that can convert arbitrary Java Objects into JSON and back, with a transparent support of any kind of self-references and with a full Java 9 compatibility.

Andrey Mogilev 9 Dec 30, 2021
A simple java JSON deserializer that can convert a JSON into a java object in an easy way

JSavON A simple java JSON deserializer that can convert a JSON into a java object in an easy way. This library also provide a strong object convertion

null 0 Mar 18, 2022
Java with functions is a small java tools and utils library.

Java with functions is a small java tools and utils library.

null 4 Oct 14, 2022
Set of support modules for Java 8 datatypes (Optionals, date/time) and features (parameter names)

Overview This is a multi-module umbrella project for Jackson modules needed to support Java 8 features, especially with Jackson 2.x that only requires

FasterXML, LLC 372 Dec 23, 2022
A modern JSON library for Kotlin and Java.

Moshi Moshi is a modern JSON library for Android and Java. It makes it easy to parse JSON into Java objects: String json = ...; Moshi moshi = new Mos

Square 8.7k Dec 31, 2022
A fast JSON parser/generator for Java.

fastjson Fastjson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON str

Alibaba 25.1k Dec 31, 2022
JSON to JSON transformation library written in Java.

Jolt JSON to JSON transformation library written in Java where the "specification" for the transform is itself a JSON document. Useful For Transformin

Bazaarvoice 1.3k Dec 30, 2022
Sawmill is a JSON transformation Java library

Update: June 25, 2020 The 2.0 release of Sawmill introduces a breaking change to the GeoIpProcessor to comply with the updated license of the MaxMind

Logz.io 100 Jan 1, 2023
Genson a fast & modular Java <> Json library

Genson Genson is a complete json <-> java conversion library, providing full databinding, streaming and much more. Gensons main strengths? Easy to use

null 212 Jan 3, 2023
Fast JSON parser for java projects

ig-json-parser Fast JSON parser for java projects. Getting started The easiest way to get started is to look at maven-example. For more comprehensive

Instagram 1.3k Dec 26, 2022
Generate Java types from JSON or JSON Schema and annotates those types for data-binding with Jackson, Gson, etc

jsonschema2pojo jsonschema2pojo generates Java types from JSON Schema (or example JSON) and can annotate those types for data-binding with Jackson 2.x

Joe Littlejohn 5.9k Jan 5, 2023
A Java annotation processor used for automatically generating better builder codes.

BetterBuilder BetterBuilder is a Java annotation processor used for automatically generating better builder codes(builder design pattern), which can m

LEO D PEN 9 Apr 6, 2021
Lean JSON Library for Java, with a compact, elegant API.

mJson is an extremely lightweight Java JSON library with a very concise API. The source code is a single Java file. The license is Apache 2.0. Because

Borislav Iordanov 77 Dec 25, 2022