如何从JSON获取最大值?

时间:2019-02-02 03:15:17

标签: json max jq

有一个这样的json文件:

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

现在我想获得foo平台的max 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

2 个答案:

答案 0 :(得分:0)

max的输入必须是一个数组。

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

答案 1 :(得分:0)

一种方法是进行选择,然后使用面向数组的内置maxmax_by中的一个来找到最大值,例如

map(select(.platform=="foo"))
| max_by(.createdAt)
| .createdAt

但是,这种方法不是很令人满意,因为它需要的空间超过了严格需要的空间。对于大型阵列,max_by面向流的版本会更好。

max_by

def max_by(s; f):
  reduce s as $s (null;
    if . == null then {s: $s, m: ($s|f)}
    else  ($s|f) as $m
    | if $m > .m then {s: $s, m: $m} else . end
    end)
  | .s ;

max_by(.[] | select(.platform=="foo"); .createdAt)
| .createdAt