Search code examples
jsonjqmaxby

Selecting 'name' with highest build number from json list


Here is my sample data, it's a list of objects in a storage bucket on Oracle cloud:

{
    "objects": [
        {
            "name": "rhel/"
        },
        {
            "name": "rhel/app-3.9.6.629089.txt"
        },
        {
            "name": "rhel/app-3.11.4.629600.txt"
        }
    ]
}

The part of the value before the '/' is a folder name, after is a filename. The last number in the filename is a build number. The desired output is the name of the object with the highest build number in the rhel folder:

$ jq -r 'some_program' file.json 
rhel/app-3.11.4.629600.txt

I can somewhat process the data to exclude the bare "rhel/" folder as follows:

$ jq -r '.objects[] | select(.name|test("rhel/."))' file.json
{
  "name": "rhel/app-3.9.6.629089.txt"
}
{
  "name": "rhel/app-3.11.4.629600.txt"
}

When I try to split this on the period jq throws an error:

$ jq -r '.objects[] | select(.name|test("rhel/.")) | split(".")' file.json
jq: error (at file.json:1): split input and separator must be strings

I was expecting to use 'map(tonumber)[-2]' on the result of the split and wrap the entirety in 'max_by()'.

How can get closer to the desired output with jq?


Solution

  • [.objects[]
     | select(.name|test("rhel/."))]
    | max_by(.name|split(".")[-2]|tonumber)
    

    produces:

    {
      "name": "rhel/app-3.11.4.629600.txt"
    }
    

    If you only want the names you could begin by extracting them:

    [.objects[].name|select(test("rhel/."))]
    | max_by(split(".")[-2]|tonumber)