如何验证JSON中是否存在JSON路径

问题描述 投票:9回答:2

在给定的json文档中,如何验证json路径是否存在?

我正在使用jayway-jsonpath并输入以下代码

JsonPath.read(jsonDocument, jsonPath)

上面的代码可能会抛出下面的异常

com.jayway.jsonpath.PathNotFoundException:没有结果的路径: $ ['a.b.c']

为了减轻它,我打算先尝试验证路径是否存在,然后再尝试使用JsonPath.read

作为参考,我阅读了以下2个文档,但无法真正得到我想要的。

  1. http://www.baeldung.com/guide-to-jayway-jsonpath
  2. https://github.com/json-path/JsonPath
json jsonpath
2个回答
7
投票

虽然您确实可以捕获异常,就像注释中提到的那样,但可能有一种更优雅的方法来检查路径是否存在,而无需在整个代码中编写try catch块。

您可以在jayway-jsonpath中使用以下配置选项:

com.jayway.jsonpath.Option.SUPPRESS_EXCEPTIONS

启用此选项后,不会引发异常。如果使用read方法,则只要未找到路径,它就会简单地返回null

[这是一个带有JUnit 5和AssertJ的示例,显示了如何使用此配置选项,避免了仅用于检查json路径是否存在的try / catch块:

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

0
投票

如果您有用例来检查多个路径,也可以使用ReadContext创建一个JsonPath对象或Configuration

    // Suppress errors thrown by JsonPath and instead return null if a path does not exist in a JSON blob.
    Configuration suppressExceptionConfiguration = Configuration
            .defaultConfiguration()
            .addOptions(Option.SUPPRESS_EXCEPTIONS);
    ReadContext jsonData = JsonPath.using(suppressExceptionConfiguration).parse(jsonString);

    for (int i = 0; i < listOfPaths.size(); i++) {
        String pathData = jsonData.read(listOfPaths.get(i));
        if (pathData != null) {
            // do something
        }
© www.soinside.com 2019 - 2024. All rights reserved.