首页 > 解决方案 > 从 Json 中检索父节点元素

问题描述

我想在过滤时检索父元素和子元素。
请找到以下 XML:

    {
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
                "price": 8.95
            },a
            {
                "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
}
                        

当我给出下面的表达式时,它只给出子元素作为输出:

Expression:
$.store.book[?(@.category== 'fiction')]
Output:
[
   {
      "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
   }
]

预期输出应该是:

 {
    "store": {
        "book": [ then the below elements

[
   {
      "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
   }
]

请帮助我使用 java 和代码片段的任何替代方案。

标签: javajsonjsonpathjayway

解决方案


不幸的是,此功能尚未实现(截至目前):请参阅Github上的这个集体问题。

但是,我相信即使库允许您通过子节点获取父节点,您也不会得到预期的结果。例如,JsonPath-Plus (JS) 允许您使用运算符在层次结构中上升一个(或多个)节点^。但是,如果您向上移动,您将获得该节点下方的所有内容,这会破坏您的情况下过滤的目的,但可能在其他情况下有效。

最简单的解决方法可能是在过滤后添加“包装”JSON 页眉/页脚,可能是使用字符串操作。如果您不喜欢这样,您可以查看 JSON 转换器。JOLT是 Java 世界中常见的一种,但还有更多。


推荐阅读