1
votes

I'm trying to parse my JSON using Ansible but hitting issues. I need the pincode from the JSON response

My sample JSON response is

{
"James Params": {
"01. name": "james bond",
"02. phone": "334455667788",
"03. height": "5.10",
"04. country": "UK",
"05. pincode": "10000",
"06. city": "london",
}
}

My playbook code is

- name: Submit and read the JSON response
  uri:
    method: GET
    url: "http://URL_UNDER_TEST"
    return_content: yes
    headers:
      Accept: application/json
  register: response

- debug:
    msg: "{{response.json.'James Params'.'05. pincode'}}"

I'm getting the below error:

fatal: [localhost]: FAILED! => {"msg": "template error while templating string: expected name or number. String: {{response.json | json_query(\"James Params\".\"05. pincode\")}}"}

Request help on this.

1

1 Answers

1
votes

Q: "pincode from the JSON response"

A: The tasks below

    - debug:
        msg: "{{ response.json['James Params']['05. pincode'] }}"
    - debug:
        msg: "{{ name }} PIN is {{ response.json[name][pincode_key] }}"
      vars:
        name: 'James Params'
        pincode_key: '05. pincode'
    - debug:
        msg: "{{ name }} PIN is {{ response.json[name][pincode_key] }}"
      vars:
        name: "{{ response.json.keys()|list|first }}"
        pincode_key: '05. pincode'
    - debug:
        msg: "{{ item }} PIN is {{ response.json[item]['05. pincode'] }}"
      loop: "{{ response.json.keys()|list }}"

give

ok: [localhost] => {
    "msg": "10000"
}

ok: [localhost] => {
    "msg": "James Params PIN is 10000"
}

ok: [localhost] => {
    "msg": "James Params PIN is 10000"
}

ok: [localhost] => (item=James Params) => {
    "msg": "James Params PIN is 10000"
}