java - 如何比较数组中的每个元素?
问题描述
{
"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
}
]
}
}
以下是我的情况: author=='Nigel Rees'.price < author=='Evelyn Waugh'.price
我的查询表达式:$.store.book[?($.store.book[?(@.author == 'Nigel Rees')].price < $.store.book[?(@.author == 'Evelyn Waugh')].price)]
我希望它会返回以下结果:
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
}
正确的表达方式是什么?
解决方案
通常,要遍历数组中的项目并执行比较,您需要使用过滤器选择器:
$.store.books[?(@.price<12.99)]
但这不允许您将项目相互比较。在该表达式中,您应该(可能取决于您正在使用的库)能够使用$
来引用 JSON 根。这将允许您与特定项目进行比较:
$.store.books[?(@.price<$.store.books[1].price)]
这会将所有书籍价格与数组中第二本书的价格进行比较。我认为这是您将使用 JSON Path 获得的最接近的结果。
我们目前正在制定 JSON 路径规范,以定义官方语法和功能集。随意打开一个问题(并链接到这个问题)来请求“多迭代器”支持,以便可以相互比较项目。
推荐阅读
- python - 熊猫不重命名列名
- kotlin - 我可以省略泛型中的类型吗?- 科特林
- typescript - Bootstrap for Next.Js Typescript 应用程序如何安装
- javascript - 如何通过javascript调用带有bootstrap 5的模态窗口?
- nginx - Nginx 入口控制器规则在不重定向的情况下向 url 添加尾部斜杠
- java - Hibernate 在每次更新时将 last_updated 列设置为 current_timestamp
- python - 按下 KIvy 按钮以更改 python 代码中的标签文本
- pyspark - PySpark:如何编写计算逻辑
- python - 如果 None 是字典中的值,则插入默认字符串
- javascript - 知道字符串中的某些内容是否在数组或对象 Js 中