javajsonjsonpathjsonparserjson-path-expression

DEFAULT_PATH_LEAF_TO_NULL in jsonPath not working


JSON

{
"abc": {
    "country": [
      {
        "city": "JODHPUR"
      }
    ]
  }
}

JSONPath Configuration

    private static final Configuration suppressExceptionConfiguration = Configuration
            .defaultConfiguration()
            .addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL)
            .addOptions(Option.SUPPRESS_EXCEPTIONS);

Accessing fields

I am trying to access a field which can exist in some of my sample json and also may not exist.

for e.g.

        DocumentContext jsonContext = JsonPath.using(suppressExceptionConfiguration).parse(json);

        String name = jsonContext.read("$.abc.name");

Error

It is giving me error and exiting.

com.jayway.jsonpath.PathNotFoundException: No results for path: $['abc']['name']

Issue

I would like the program to continue and return null for this element and this is why I used option like Option.DEFAULT_PATH_LEAF_TO_NULL but it is not working.

My environment

Java 17

JSONPath version

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

Solution

  • Debugging

    After debugging jsonPath code using breakpoints in intellij IDE, Realised we need to pass Configuration in each instance of DocumentContext.

    For e.g.

    Configuration

        private static final Configuration suppressExceptionConfiguration = Configuration
                .defaultConfiguration()
                .addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL)
                .addOptions(Option.SUPPRESS_EXCEPTIONS);
    

    Example

    Pass above configuration in each instance of DocumentContext to make sure configuration is always applied and not missed.

            DocumentContext jsonContext = JsonPath.using(suppressExceptionConfiguration).parse(json);
            DocumentContext name = JsonPath.parse((String) jsonContext.read("$.abc.name"), suppressExceptionConfiguration);