Home > other >  JOLT spec - Is it possible to sort values according key/value of a list of dict?
JOLT spec - Is it possible to sort values according key/value of a list of dict?

Time:12-16

JSON Input :

{
  "list": [
    {
      "tags": [
        {
          "scope": "",
          "tag": "TAG_VM"
        },
        {
          "scope": "",
          "tag": "TAG_HOST"
        },
        {
          "scope": "",
          "tag": "TAG_ROLE_DNS"
        },
        {
          "scope": "",
          "tag": "TAG_ROLE_AD"
        }
      ]
    }
  ],
  "result_count": 1,
  "sort_by": "name"
}

Desired Output :

{
  "role1" : "DNS",
  "role2" : "AD"
}

(sorting value on the last "string" after the last "_")

I already tried this but it doesnt work :

[
  {
    "operation": "shift",
    "spec": {
      "list": {
        "*": {
          "tags": {
            "*": {
              "tag": {
                "TAG_ROLE*": "role1"
              }
            }
          }
        }
      }
    }
  }
]

Does somebody knows how to use properly JOLT ? I'm kinda lost with it

CodePudding user response:

Let's constuct it in a dynamical manner such as :

[
  { // extact literals from the asterisks followed by TAG_ROLE_ through going one level up and take the value of first asterisk(already exists one, but might be more than one) by using &(1 --> level up ,1 --> first asterisk)
    "operation": "shift",
    "spec": {
      "*": {
        "*": {
          "*": {
            "*": {
              "*": {
                "TAG_ROLE_*": {
                  "#r": "&(1,1)"
                }
              }
            }
          }
        }
      }
    }
  },
  { // build an array, namely "r" by exchanging key-value pairs, while adding a fake first component to be used for extra increment of the index value, as indexes start from zero, but we need them to start from one in the upcoming spec 
    "operation": "shift",
    "spec": {
      "*": {
        "$": "@(0)"
      },
      "#0": "r"
    }
  },
  { // we tiled the key-value pairs as desired except for the one with zero key
    "operation": "shift",
    "spec": {
      "*": {
        "*": {
          "@": "role&"
        }
      }
    }
  },
  { // get rid of the first(fake) component
    "operation": "remove",
    "spec": {
      "*0": ""
    }
  }
]
  • Related