Shubhi
Shubhi

Reputation: 11

Ansible: Get Particular value from JSON

I am getting following output in Ansible JSON Format and need to fetch Request ID from it please help

ok: [localhost] => {
    "op.content": {
        "_links": {
           "self": [
               {
                   "href": "url123"
               }
           ]
        }, 
       "entries": [
            {
               "_links": {
                  "self": [
                       {
                           "href": "url456"
                        }  
                ] 
            }, 
            "values": {
                "Request ID": "abc|abc", 
                "Status": "Assigned"
            }
        }
    ]
}

}

Upvotes: 1

Views: 4971

Answers (1)

guzmonne
guzmonne

Reputation: 2540

You can use the json_query filter to get the Request ID value of your JSON object. Here is an example of how you could parse it. In my example, I am getting the JSON object from a file, and storing it in a variable called op_request. On the json_query task, take notice of how you can escape a key that has a dot (.) inside:

---
- name: Get "Request ID" from JSON
  hosts: all
  connection: local
  gather_facts: no
  vars_files:
    - ./secret.yml
  vars:
    op_content_file: ./files/op_content.json
  tasks:
    - name: Read JSON file
      set_fact:
        op_content: '{{ lookup("file", op_content_file) }}'

    - name: Get RequestID from op_content variable
      set_fact:
        request_id: "{{ op_content | json_query('\"op.content\".entries[0].values.\"Request ID\"') }}"

I hope it helps

Upvotes: 1

Related Questions