Get json object that has latest timestamp using jq

北城以北 提交于 2021-02-08 05:09:16

问题


I have a below json file but I'm struggling to only display the description with the latest createdDate.

I tried with

>
<
todateiso8601?
now

and a few more but I can't get this to work.

Would anyone be able to help?

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"
        }
]
}

回答1:


Simply sort by .createdDate and (assuming you only want one value even if there is more than one with the greatest .createdDate value), select the last one:

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

Ties

If you want all the descriptions in the case of ties:

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



回答2:


EDIT: use peaks answer it is superior

Here is a simple script that does this in 2 commands. Probably can be done in 1 but alas my nooblet skills were not enough

You can pipe to max with an array of numbers in JQ and it will return the largest value in the input array.

Then we use select to grab the object containing the max value and output the description.

We will also use arg which allows us to reference a local environment variable, and we need to cast it to a number or JQ thinks it's a string.

maxDate=$(cat tmp.json | jq '[.items[].createdDate] | max')

cat tmp.json | jq --arg maxDate "$maxDate" '.[][] | select(.createdDate == ($maxDate | tonumber)).description'

Output:

"this is description 2"

In the future, please post your desired output as well as your question so responders can be confident they are solving the problem to your liking



来源:https://stackoverflow.com/questions/56758079/get-json-object-that-has-latest-timestamp-using-jq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!