如何从 JSON 中获取最大值?

zhu*_*wei 3 json max jq

有一个这样的json文件:

[
{
    "createdAt": 1548729542000,
    "platform": "foo"
},
{
    "createdAt": 1548759398000,
    "platform": "foo"
},
{
    "createdAt": 1548912360000,
    "platform": "foo"
},
{
    "createdAt": 1548904550000,
    "platform": "bar"
}
]
Run Code Online (Sandbox Code Playgroud)

现在我想获得 foo 平台的最大 createdAt 吗?如何通过使用 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
Run Code Online (Sandbox Code Playgroud)

ogu*_*ail 7

max 期望一个数组作为输入。

$ jq '[ .[] | select(.platform == "foo").createdAt ] | max' file
1548912360000
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,我一直在通过反复试验来解决这个问题...我发现返回的行(不是数组本身,但每行可能是一个数组)和将行收集到数组中并返回之间的区别令人困惑。不过你的回答对我有帮助。 (2认同)