选择和过滤数组中的最新元素
Selecting and filtering latest element in array
我有以下示例数据:
{
"Images": [
{
"Name": "CoreOS-alpha-1939.0.0-hvm",
"CreationDate": "2014-12-24T23:00:48.000Z"
},
{
"Name": "CoreOS-stable-522.3.0",
"CreationDate": "2014-12-24T23:00:48.000Z"
},
{
"Name": "CoreOS-stable-600.3.0",
"CreationDate": "2019-12-24T23:00:48.000Z"
}
]
}
我正在尝试获取最新(CreationDate
)图像的 Name
,该图像的 Name
.
中包含 "stable"
我天真的尝试是:
jq '.Images[] | select(.Name | contains("stable")) |= sort_by(.CreationDate)' data.json
但是这给了我一个错误,并且只会按 CreationDate
对它们进行排序(不仅是 return 最新的)
$ jq -r '.Images | map(select(.Name | index("stable"))) | max_by(.CreationDate).Name' file
CoreOS-stable-600.3.0
因为 contains
对于检查一个字符串是否包含在另一个字符串中有点矫枉过正,因此使用 index
代替。
使用 max_by
是因为它避免排序并产生最大值的元素。 CreationDate
。
我有以下示例数据:
{
"Images": [
{
"Name": "CoreOS-alpha-1939.0.0-hvm",
"CreationDate": "2014-12-24T23:00:48.000Z"
},
{
"Name": "CoreOS-stable-522.3.0",
"CreationDate": "2014-12-24T23:00:48.000Z"
},
{
"Name": "CoreOS-stable-600.3.0",
"CreationDate": "2019-12-24T23:00:48.000Z"
}
]
}
我正在尝试获取最新(CreationDate
)图像的 Name
,该图像的 Name
.
我天真的尝试是:
jq '.Images[] | select(.Name | contains("stable")) |= sort_by(.CreationDate)' data.json
但是这给了我一个错误,并且只会按 CreationDate
对它们进行排序(不仅是 return 最新的)
$ jq -r '.Images | map(select(.Name | index("stable"))) | max_by(.CreationDate).Name' file
CoreOS-stable-600.3.0
因为 contains
对于检查一个字符串是否包含在另一个字符串中有点矫枉过正,因此使用 index
代替。
使用 max_by
是因为它避免排序并产生最大值的元素。 CreationDate
。