有这样一个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
max
的输入必须是一个数组。
$ jq '[ .[] | select(.platform == "foo").createdAt ] | max' file
1548912360000
一种方法是进行选择,然后使用面向阵列内建max
或max_by
之一以找到最大,例如
map(select(.platform=="foo"))
| max_by(.createdAt)
| .createdAt
然而,因为它需要更多的空间比是绝对必要的这种做法也不是很理想。对于大型阵列,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