首页 > 解决方案 > 使用 jq 获取具有最新时间戳的 json 对象

问题描述

我有一个下面的 json 文件,但我正在努力只显示description最新的createdDate.

我试过了

>
<
todateiso8601?
now

还有一些,但我无法让它工作。

有人能帮忙吗?

JSON:

{
    "items": [
        {
            "createdDate": 1543585940, 
            "id": "awefef", 
            "description": "this is description 1"
        }, 
        {
            "createdDate": 1555324487, 
            "id": "hjkvhuk", 
            "description": "this is description 2"
        }, 
        {
            "createdDate": 1547034297, 
            "id": "xdfxdfv", 
            "description": "this is description 3"
        }
]
}

标签: jsonjq

解决方案


只需按 .createdDate 排序并(假设您只需要一个值,即使有多个具有最大 .createdDate 值的值),选择最后一个:

.items
| sort_by(.createdDate)[-1].description

领带

如果您想要关系的所有描述:

.items
| sort_by(.createdDate)
| (.[-1].createdDate) as $max
| .[]
| select($max == .createdDate)
| .description

推荐阅读