4

这是我的 JSONtest.json文件:

[
  {
    "name": "nodejs",
    "version": "0.1.21",
    "apiVersion": "v1"
  },
  {
    "name": "nodejs",
    "version": "0.1.20",
    "apiVersion": "v1"
  },
  {
    "name": "nodejs",
    "version": "0.1.11",
    "apiVersion": "v1"
  },
  {
    "name": "nodejs",
    "version": "0.1.9",
    "apiVersion": "v1"
  },
  {
    "name": "nodejs",
    "version": "0.1.8",
    "apiVersion": "v1"
  }
]

当我使用max_by时,jq返回0.1.9而不是0.1.21可能由于引用的值:

cat test.json | jq 'max_by(.version)'
{
  "name": "nodejs",
  "version": "0.1.9",
  "apiVersion": "v1"
}

如何获取 version=0.1.21 的元素?

4

2 回答 2

4

不支持开箱即用的语义版本jq比较。你需要玩弄分割的字段.

jq 'sort_by(.version | split(".") | map(tonumber))[-1]'

split(".")获取字符串并创建一个字段数组,.version0.1.21成为一个数组[ "0", "1", "21"]map(tonumber)获取一个输入数组并将字符串元素转换为数字数组。

The sort_by() function does a index wise comparison for each of the elements in the array generated from last step and sorts in the ascending order with the object containing the version 0.1.21 at the last. The notation [-1] is to get the last object from this sorted array.

于 2019-07-17T08:08:45.070 回答
2

Here's an adaptation of the more general answer using jq at How to sort Artifactory package search result by version number with JFrog CLI?

def parse:
 [splits("[-.]")]
 | map(tonumber? // .) ;

max_by(.version|parse)

As a less robust one-liner:

max_by(.version | [splits("[.]")] | map(tonumber))
于 2019-07-17T08:18:38.877 回答