【问题标题】:how to Validate if JSON Path Exists in JSON如何验证 JSON 路径是否存在于 JSON 中
【发布时间】:2017-09-07 19:44:03
【问题描述】:

在给定的 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

【问题讨论】:

  • 为什么不捕获异常并以这种方式处理呢?
  • 我可以这样做,但认为在读取之前验证路径会是一种更简洁的方法
  • 不一定 - 检查路径可能比捕获此特定异常更昂贵
  • 在性能方面达成一致。只是想知道是否有 API 来验证路径是否存在。

标签: json jsonpath


【解决方案1】:

如果您有检查多条路径的用例,您还可以创建 JsonPath 对象或带有 ConfigurationReadContext

    // 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
        }

【讨论】:

    【解决方案2】:

    虽然确实可以捕获异常,就像 cmets 中提到的那样,但可能有一种更优雅的方法来检查路径是否存在,而无需在整个代码中编写 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();
    }
    

    【讨论】:

    • 但是使用这种方法,如果路径存在但它的元素值为 null - 我们也会得到 null,对吧?
    猜你喜欢
    • 2014-09-03
    • 2016-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    • 2018-01-10
    相关资源
    最近更新 更多