0

我有一个用例,我需要 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
 }

        ] 
  }
}
4

1 回答 1

0

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

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

但是,您也许可以从路径中推断出您需要什么。该项目的路径是$.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],您仍然会得到与您发布的相同的嵌套结构。(不是在这里讨论它是如何工作的;只是解释为什么现在不行。)

于 2021-07-04T05:30:00.643 回答