5

I need some help using jq to sort an array of elements where each element contains a nested tags array of elements. My input JSON looks like this:

{
  "result": [
    {
      "name": "ct-1",
      "tags": [
        {
          "key": "service_name",
          "value": "BaseCT"
        },
        {
          "key": "sequence",
          "value": "bb"
        }
      ]
    },
    {
      "name": "ct-2",
      "tags": [
        {
          "key": "service_name",
          "value": "BaseCT"
        },
        {
          "key": "sequence",
          "value": "aa"
        }
      ]
    }
  ]
}

I would like to sort using the value of the sequence tag in the nested tags array so that the output looks like this:

{
  "result": [
    {
      "name": "ct-2",
      "tags": [
        {
          "key": "service_name",
          "value": "BaseCT"
        },
        {
          "key": "sequence",
          "value": "aa"
        }
      ]
    },
    {
      "name": "ct-1",
      "tags": [
        {
          "key": "service_name",
          "value": "BaseCT"
        },
        {
          "key": "sequence",
          "value": "bb"
        }
      ]
    }
  ]
}

I have tried the following jq command:

$ jq '.result |= ([.[] | .tags[] | select(.key == "sequence") | .value] | sort_by(.))' input.json

but I get the following result:

{
  "result": [
    "aa",
    "bb"
   ]
}

Please let me know if you know how to deal with this scenario.

oguz ismail
  • 1
  • 16
  • 47
  • 69
Sanjay Saxena
  • 365
  • 1
  • 5
  • 8

1 Answers1

5

from_entries converts an array of key-value pairs to an object, you can use it with sort_by like this:

.result |= sort_by(.tags | from_entries | .sequence)
oguz ismail
  • 1
  • 16
  • 47
  • 69