【问题标题】:Exclude fields from JSON using JSONPath使用 JSONPath 从 JSON 中排除字段
【发布时间】:2015-03-05 09:31:22
【问题描述】:

我从 REST 服务调用中获得 JSON 响应,并且只想从响应中选择一些字段。我正在使用 JSONPath 过滤掉这些字段。下面是 JSON 示例:

{
    "store": {
        "book": [{
            "category": "reference",
            "author": "Nigel Rees",
            "title": "Sayings of the Century",
            "price": 8.95
        },
        {
            "category": "fiction",
            "author": "Evelyn Waugh",
            "title": "Sword of Honour",
            "price": 12.99
        },
        {
            "category": "fiction",
            "author": "Herman Melville",
            "title": "Moby Dick",
            "isbn": "0-553-21311-3",
            "price": 8.99
        },
        {
            "category": "fiction",
            "author": "J. R. R. Tolkien",
            "title": "The Lord of the Rings",
            "isbn": "0-395-19395-8",
            "price": 22.99
        }],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    }
}

例如我想从类别为“参考”的响应中选择作者和标题。我正在使用下面的 JSONPath

$.store.book[?(@.category='reference')]

这给了我以下回应:

{
    "category": "reference",
    "author": "Nigel Rees",
    "title": "Sayings of the Century",
    "price": 8.95
}

但是,我不想要所有字段。我只想要作者和标题。如果我尝试$.store.book[?(@.category='reference')]['author'],它会给我作者姓名,但如果我尝试$.store.book[?(@.category='reference')]['author', 'title'],它不会返回任何内容。

JSONPath 中是否有任何规定可以选择(或排除)有条件或无条件的字段?

我正在使用http://jsonpath.curiousconcept.com/ 来测试 JSONPath。

提前致谢。

【问题讨论】:

    标签: json jsonpath


    【解决方案1】:

    如果你试试这个会怎样:

    $.store.book[?(@.category='reference')]['author']['title']
    

    【讨论】:

    • $.store.book[?(@.category='reference')]['title'] 是否返回任何东西?
    【解决方案2】:

     $ jq '.store.book[] | select(.category=="reference") | .author, .title' json
    

    输出:

    "Nigel Rees"
    "Sayings of the Century"
    

    【讨论】:

    • 感谢您的回复。我们可以使用 JSONPath 而不是 jq 来做同样的事情吗?我们在后端使用 JSONPath 库,并不想将其更改为 jq,因为许多其他 api 都在使用它。
    【解决方案3】:

    使用Jayways JsonPath (Java) 可以:

    $.store.book[?(@.category == 'reference')]['author', 'title']
    

    测试不同的实现here

    【讨论】:

      【解决方案4】:

      您的帖子没有说明您使用的是 Goessner 还是 Flow Communications JSON 路径表达式评估器。两者都可以在您使用的表达式测试器站点上找到。如果您使用的是 Goessner,则以下查询有效,但不适用于您正在使用的表达式测试站点

      $.store.book[?(@.category=='reference')]['author','title']
      

      注意双等号 (@.category=='reference') 而不是单等号。此外,选择字段'author','title' 的逗号后不应有空格。

      你可以在这里看到表达式 http://www.jsonquerytool.com/sample/jsonpathselectmultiplefields

      【讨论】:

      • 在我的情况下,我想维护“路径”结构 - 这可能吗:所以结果将是以下形式:{“store”:{“book”:[{“author” : "Nigel Rees", "title": "世纪语录"}]}}?
      猜你喜欢
      • 1970-01-01
      • 2015-05-19
      • 1970-01-01
      • 2017-10-18
      • 1970-01-01
      • 2022-11-18
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      相关资源
      最近更新 更多