【问题标题】:JSON Path to return whole json which matches predicate返回与谓词匹配的整个 json 的 JSON 路径
【发布时间】:2021-07-04 03:03:18
【问题描述】:

我有一个用例,我需要 JSON 路径来返回与其谓词匹配的整个 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
  }
  },
    "expensive" : 10
}

这是我的json path expression

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

返回

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

]

但我想要整个路径,如下所示,

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

        ] 
  }
}

【问题讨论】:

    标签: java json jsonpath


    【解决方案1】:

    这不是 JSON Path 通常可以做的事情,但请检查您的具体实现。

    通常 JSON 路径可以返回匹配项或它们的路径。不支持在原始结构中嵌套匹配。

    但是,您也许可以从路径中推断出您需要什么。该项目的路径是$.store.book[0]。要重建您想要的对象,您需要...

    $        // start, no impact
    .store  // create an object with "store"
    .book   // create an object with "book"
    [0]     // since this is the last thing, replace this with the match
    

    看看这个,如果匹配在数组中而不是在开始时,尝试支持这一点似乎会出现问题。例如,如果您匹配的是[2] 而不是[0],您仍然会得到与您发布的相同的嵌套结构。 (这里不是讨论它是如何工作的;只是解释为什么现在不行。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-21
      • 1970-01-01
      • 1970-01-01
      • 2016-06-02
      • 2017-06-28
      • 2021-07-06
      • 2020-02-15
      • 1970-01-01
      相关资源
      最近更新 更多