返回与谓词匹配的整个 json 的 JSON 路径

时间:2021-07-04 03:03:18

标签: java json jsonpath

我有用例,我需要 JSON 路径来返回与其谓词匹配的整个 json 结构。

sapply(data0, function(x) which(is.na(x))[seq_along(x)])

#      A  B  C  D
#[1,]  1  2  3 NA
#[2,]  2 NA  4 NA
#[3,] NA NA NA NA
#[4,] NA NA NA NA

这是我的 { "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
 }

1 个答案:

答案 0 :(得分: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],您仍然会得到与您发布的相同的嵌套结构。 (不是在这里讨论这是如何工作的;只是解释为什么现在不行。)