6

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.

1 Answer 1

7

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.