Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using keys from the json src doc in a multiselect hash with Jmespath

I have a source json document that looks like this:

# Source json
{
  "nics": {
    "vlan_internal": {
      "mac": "aa:aa:aa:aa:aa:aa"
    },
    "vlan_external": {
      "mac": "aa:aa:aa:aa:aa:bb"
    }
  }
}

Using ansible's json_query filter (which uses jmespath), I want to manipulate the json above so that the output json document looks like this:

# Desired output json
{
  "vlan_internal": "aa:aa:aa:aa:aa:aa",
  "vlan_external": "aa:aa:aa:aa:aa:ab"
}

It seems that I should be using a multiselect hash of some kind, but I can't find a good way to get the vlan names (which are hash keys in the source json doc, not hash values) into the output json doc.

I won't know the names of the vlans ahead of the time, so I can't hardcode vlan_internal or vlan_external into the jmespath expression.

The closest I've come is with this jmespath expression:

nics.{ vlans: keys(@), macs: *.mac }

Which results in an output json doc that was almost-useful:

{
  "vlans": [
    "vlan_internal",
    "vlan_external"
  ],
  "macs": [
    "aa:aa:aa:aa:aa:aa",
    "aa:aa:aa:aa:aa:bb"
  ]
}

This would have worked for me if it were guaranteed that the order of the list of vlan names and the order of the list of mac addresses was the same as that of the source json document. But the jmespath specification makes it very clear that the keys() function is not required to return results in any specific order. Since I need to pair up a vlan name with the correct mac address, this won't work for me.

Does someone know a way to accomplish this with jmespath?

like image 641
loudsong Avatar asked Nov 07 '22 22:11

loudsong


1 Answers

With only JMESPath you can use this query:

@.nics | {vlan_internal: @.vlan_internal | values(@)[0], vlan_external: @.vlan_external | values(@)[0]}

with this your source JSON you will get:

{
  "vlan_internal": "aa:aa:aa:aa:aa:aa",
  "vlan_external": "aa:aa:aa:aa:aa:bb"
}
like image 84
bosskay972 Avatar answered Nov 15 '22 06:11

bosskay972