barbiepylon
barbiepylon

Reputation: 911

Remove brackets from ansible json_query

I'm trying to parse json in ansible and I got the value I need but the output is an array. How can I get just the value?

Example json:

{
"Version": "2015-08-13",
"Accounts": [{
    "AccountName": "account1",
    "Regions": [{
        "RegionName": "region1",
        "RegionId": "region1",
        "RegionDetails": [{
            "id": "id1",
            "version": "v1"
        }, {
            "id": "id2",
            "version": "v2"
        }]
    }]
}, {
    "AccountName": "account2",
    "Regions": [{
        "RegionName": "region1",
        "RegionId": "region1",
        "RegionDetails": [{
            "id": "id1",
            "version": "v1"
        }, {
            "id": "id2",
            "version": "v2"
        }]
    }]
}]
}

Ansible playbook example:

    - name: Set Global Vars
      hosts: localhost
      tasks:    
        - name: print json file
          debug:
            msg: "{{ (lookup('file','./example.json') | from_json) | json_query(query) }}"
          vars:
            query: "Accounts[?AccountName=='account1'][Regions[?RegionName=='region1'].RegionId]"
      register: region_id

Ansible output:

    TASK [print json file] *********************************************************
ok: [localhost] => {
    "msg": [
        [
            [
                "region1"
            ]
        ]
    ]
}

As you can see the value 'region1' is still nested. How can I get just the value out?

Thanks!

Upvotes: 1

Views: 5155

Answers (1)

Konstantin Suvorov
Konstantin Suvorov

Reputation: 68269

Your original data has nested lists: Accounts is a list, each account contains Regions list.

With your JMESPath query you filter lists by some criteria, but result is still a list, because your data may have more then one account with name AccountName=='account1'.

If you are interested only in first found account and first found region of that account, you can modify query as follows:

Accounts[?AccountName=='account1'] | [0].Regions[?RegionName=='region1'] | [0].RegionId

Upvotes: 4

Related Questions