如何从一个JSON最大值?

问题描述 投票:1回答:2

有这样一个JSON文件:

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

现在,我想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
json max jq
2个回答
0
投票

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

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

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
© www.soinside.com 2019 - 2024. All rights reserved.