有一个这样的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 'map(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
为什么不:
jq -c '.[] | select(.platform=="foo") | .createdAt' | sort -un | tail -1
JSON -> 数字列表 -> 按数字排序,asc -> 获取最后一个(最大值)