java - 从 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 和代码片段的任何替代方案。
解决方案
不幸的是,此功能尚未实现(截至目前):请参阅Github上的这个集体问题。
但是,我相信即使库允许您通过子节点获取父节点,您也不会得到预期的结果。例如,JsonPath-Plus (JS) 允许您使用运算符在层次结构中上升一个(或多个)节点^
。但是,如果您向上移动,您将获得该节点下方的所有内容,这会破坏您的情况下过滤的目的,但可能在其他情况下有效。
最简单的解决方法可能是在过滤后添加“包装”JSON 页眉/页脚,可能是使用字符串操作。如果您不喜欢这样,您可以查看 JSON 转换器。JOLT是 Java 世界中常见的一种,但还有更多。
推荐阅读
- javascript - 将字段设置为数组中的对象,Vega-lite
- lua - LUA:无法理解 ax 和 a[x] 之间的区别
- reactjs - 如何使用语义 UI 显示单个表单输入的错误消息?
- xaml - 使用 Uno.Platform ElevatedView 居中阴影
- r - 根据另一列中组的第一个实例减去一个值
- toad - Toad - 复制到另一个模式时出错“未为任何表配置 Where 子句。”
- javascript - 无法设置机器人的头像不和谐js
- python - 具有高维数据集的层次聚类图
- python - 盈透证券 Python API:contractDetails 请求打印良好,但不会返回
- ios - 上传任务完成后可以启动后台任务吗?