Search code examples
ansiblejson-query

How to filter remove square bracket in json_query?


i have below json file and i am trying to filter the value but getting double square bracket but i want to remove the first square bracket using the regex_replace but dont how this works.. this json file getting store in variable called config_params from there i trying to filter..

{
  "servers": {
    "server_details": [
      {
        "srv_make": "hp",
        "newip_address": "192.168.200.139",
        "newhostname": "hostbh1",
        "nic_macaddress": {
          "nic1-mac1_nic2-mac1": [
            "b8:83:03:81:4b:20",
            "b8:83:03:84:d5:1c"
          ],
          "nic1-mac2_nic2-mac2": [
            "b8:83:03:81:4b:20",
            "b8:83:03:84:d5:1c"
          ]
        },
        "vmotion_ip_address": "10.10.20.36",
        "iscsi_ip_address": "192.168.0.36",

      }
    ]
  }
}

mac_group_list: "{{ config_params | json_query('servers.server_details[*].nic_macaddress.nic1-mac1_nic2-mac1') }}"

        [
          [
            "b8:83:03:81:4b:20",
            "b8:83:03:84:d5:1c"
          ]
        ]

I am expecting the out put as below- how can i achieve this in json query.

  [
    "b8:83:03:81:4b:20",
    "b8:83:03:84:d5:1c"
  ]

Thanks


Solution

  • Your result is a list of lists, and you want the first element. You could simply ask for the first element, like this:

    mac_group_list: >-
      {{ inputjson | json_query('servers.server_details[].nic_macaddress."nic1-mac1_nic2-mac1"')[0] }}"
    

    Or you could use the flatten filter:

    mac_group_list: >-
      {{ inputjson | json_query('servers.server_details[].nic_macaddress."nic1-mac1_nic2-mac1"') | flatten }}
    

    You can also probably fix your query, but that's harder to answer without seeing what the original data looks like.

    Update

    Or you could write your query filter like this:

    - set_fact:
        output: >-
          {{
            inputjson |
            json_query('servers.server_details[].nic_macaddress[]."nic1-mac1_nic2-mac1"[]')
          }}
    

    I've reformatted it for readability, but that's effectively exactly what you have now with an extra [] at the end. Given your sample data -- fixed to meet the assumptions I described in a comment on your question -- this produces:

    TASK [debug] *********************************************************************************************************************************************************************************
    ok: [localhost] => {
        "output": [
            "b8:83:03:81:4b:20",
            "b8:83:03:84:d5:1c"
        ]
    }