Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to Validate if JSON Path Exists in JSON

Tags:

json

jsonpath

In a given json document, how to validate if a json path exists ?

I am using jayway-jsonpath and have the below code

JsonPath.read(jsonDocument, jsonPath)

The above code can potentially throw below exception

com.jayway.jsonpath.PathNotFoundException: No results for path: $['a.b.c']

In order to mitigate it, I intend to validate if the path exists before trying to read it with JsonPath.read

For reference I went through the following 2 documentations, but couldn't really get what I want.

  1. http://www.baeldung.com/guide-to-jayway-jsonpath
  2. https://github.com/json-path/JsonPath
like image 910
Vinod Jayachandran Avatar asked Apr 12 '17 07:04

Vinod Jayachandran


People also ask

How do I check if a JSON path is valid?

Try importing Jayway JsonPath then JsonPath. read("{}", yourJsonPath); and if it doesn't explode the path is valid.

How do you evaluate a JSON path?

You can open up a window to evaluate JSONPath expressions by going to Edit -> Find -> "Evaluate JSONPath Expression...". If a JSON file is open, it will use this file to evaluate the expression. If you have JSONPath expressions as Strings in code, use "inject language" and say this is a JSONPath expression.

What is a valid JSON path?

A JSONPath expression specifies a path to an element (or a set of elements) in a JSON structure. Paths can use the dot notation: $.store.book[0].title. or the bracket notation: $['store']['book'][0]['title']

Is JSONPath fast?

JsonPath seems to be pretty slow for large JSON files. In my project, I'd like a user to be able to pass an entire query as a string. I used JsonPath because it lets you do an entire query like $. store.


1 Answers

Whilst it is true that you can catch an exception, like it is mentioned in the comments there might be a more elegant way to check if a path exists without writing try catch blocks all over the code.

You can use the following configuration option with jayway-jsonpath:

com.jayway.jsonpath.Option.SUPPRESS_EXCEPTIONS

With this option active no exception is thrown. If you use the read method, it simply returns null whenever a path is not found.

Here is an example with JUnit 5 and AssertJ showing how you can use this configuration option, avoiding try / catch blocks just for checking if a json path exists:

@ParameterizedTest
@ArgumentsSource(CustomerProvider.class)
void replaceStructuredPhone(JsonPathReplacementArgument jsonPathReplacementArgument) {
    DocumentContext dc = jsonPathReplacementHelper.replaceStructuredPhone(
            JsonPath.parse(jsonPathReplacementArgument.getCustomerJson(),
                    Configuration.defaultConfiguration().addOptions(Option.SUPPRESS_EXCEPTIONS)),
            "$.cps[5].contactPhoneNumber", jsonPathReplacementArgument.getUnStructuredPhoneNumberType());
    UnStructuredPhoneNumberType unstructRes = dc.read("$.cps[5].contactPhoneNumber.unStructuredPhoneNumber");
    assertThat(unstructRes).isNotNull();
    // this path does not exist, since it should have been deleted.
    Object structRes = dc.read("$.cps[5].contactPhoneNumber.structuredPhoneNumber");
    assertThat(structRes).isNull();
}
like image 189
gil.fernandes Avatar answered Sep 27 '22 16:09

gil.fernandes