jq - 获取具有最新日期的对象
Json 看起来像这样:
cat test.json |jq -r ".nodes[].run_data"
{
"id": "1234",
"status": "PASSED",
"penultimate_status": "PASSED",
"end_time":"2022-02-28T09:50:05Z"
}
{
"id": "4321",
"status": "PASSED",
"penultimate_status": "UNKNOWN",
"end_time": "2020-10-14T13:52:57Z"
}
我想获取最新运行的“状态”和“结束时间”。不幸的是订单没有固定。这意味着最新的运行可以是列表中的第一个,但也可以是最后一个或中间......
Json looks like this:
cat test.json |jq -r ".nodes[].run_data"
{
"id": "1234",
"status": "PASSED",
"penultimate_status": "PASSED",
"end_time":"2022-02-28T09:50:05Z"
}
{
"id": "4321",
"status": "PASSED",
"penultimate_status": "UNKNOWN",
"end_time": "2020-10-14T13:52:57Z"
}
I want to get "status" and "end_time" of the newest run. Unfortunately the order is not fix. Meaning the newest run can be first in the list, but also last or in the middle...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
transpose
将每个对象与其 end_time 进行映射。在这里,我将
end_time
转换为自 Unix 纪元以来的秒数,并输出具有最大秒值的对象(这是最新的)。输出
演示
https://jqplay.org/s/w1z2n2drc7
You can use
transpose
to map each object with its end_time.Here I have converted
end_time
to seconds since Unix epoch and outputted the object with largest seconds value (this is the newest).Output
Demo
https://jqplay.org/s/w1z2n2drc7
您可以使用
max_by
检索具有最高谓词值的项目。或者,使用sort_by
将项目沿着谓词按顺序排列,然后使用last
或位置-1
提取最后一个项目:生成格式化输出,将
{status, end_time}
替换为相应格式的字符串,例如"\(.end_time): Status \(.status)"
,然后设置-r
标志JSON 解码(原始)输出。You could use
max_by
to retrieve the item with the highest predicate value. Alternatively, usesort_by
to bring the items in order along that predicate, then extract the last item using eitherlast
or the position-1
:To generate a formatted output, replace
{status, end_time}
with an accordingly formatted string, e.g."\(.end_time): Status \(.status)"
, and set the-r
flag for a JSON-decoded (raw) output.