如何使用JMESPath获取带xxx前缀的最新文件元素
使用JMESPath筛选带xxx前缀且时间最新的文件
输入JSON
{ "details": [ { "file": [ "xxx-abc" ], "filePushedAt": "2021-10-25T09:31:39+02:00" }, { "file": [ "xxx-dfg" ], "filePushedAt": "2021-11-08T16:24:05+01:00" }, { "file": [ "hij" ], "filePushedAt": "2022-01-26T15:24:17+01:00" }, { "file": [ "xxx-klm" ], "filePushedAt": "2022-01-27T15:24:18+01:00" }, { "file": [ "opr" ], "filePushedAt": "2021-11-28T09:31:39+02:00" } ] }
需求
提取file数组中带xxx前缀,且filePushedAt时间最新的文件,要求仅使用JMESPath,不借助jq。
已实现按时间排序提取文件名的JMESPath语句:
sort_by(details,& filePushedAt)[*].file[*]
解决方案
完全可以仅用JMESPath完成,只需结合过滤、排序和取值三步:
最终JMESPath表达式
sort_by(details[?starts_with(file[0], 'xxx')], &filePushedAt)[-1].file[0]
分步解释
- 过滤带xxx前缀的条目:用
starts_with(file[0], 'xxx')筛选出file数组第一个元素以xxx开头的项details[?starts_with(file[0], 'xxx')] - 按时间排序:对过滤后的结果用
sort_by按filePushedAt升序排列,最新的条目会排在最后sort_by(details[?starts_with(file[0], 'xxx')], &filePushedAt) - 取最新的文件名:用
[-1]取排序后的最后一项,再提取file[0]拿到目标文件名
执行后返回结果:"xxx-klm"
内容的提问来源于stack exchange,提问作者Murakami
相关产品推荐
相关产品推荐

