Search code examples
jsonmaxjq

How to get max value from JSON?


There is a json file like this:

[
{
    "createdAt": 1548729542000,
    "platform": "foo"
},
{
    "createdAt": 1548759398000,
    "platform": "foo"
},
{
    "createdAt": 1548912360000,
    "platform": "foo"
},
{
    "createdAt": 1548904550000,
    "platform": "bar"
}
]

Now I want to get the max createdAt of foo platform? how to implement it by using jq?

jq '.[] | select(.platform=="foo") | .createdAt | max' foo.json
jq: error (at <stdin>:17): number (1548729542000) and number (1548729542000) cannot be iterated over

jq '.[] | select(.platform=="foo") | max_by(.createdAt)' foo.json
jq: error (at <stdin>:17): Cannot index number with string "createdAt"
exit status 5

Solution

  • max expects an array as input.

    $ jq 'map(select(.platform == "foo") .createdAt) | max' file
    1548912360000