How to check if JSON path exists in JSON

In this json document, how to check if a json path exists?

I am using jayway-jsonpath and has the following code

JsonPath.read(jsonDocument, jsonPath)

The above code could potentially throw an exception

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

To mitigate it, I intend to check if a path exists before trying to read it with JsonPath.read

For reference, I looked at the following 2 documentation, but could not get what I want.

+4
source share
1 answer

, , , , try catch .

jayway-jsonpath:

com.jayway.jsonpath.Option.SUPPRESS_EXCEPTIONS

. read, null , .

JUnit 5 AssertJ, , , try/catch , json:

@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();
}
+2

Source: https://habr.com/ru/post/1674630/


All Articles