Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse json value when value contains a string in ansible

Tags:

json

ansible

This ansible playbook works

---
- hosts: localhost
  gather_facts: False

  vars:
    jq: "[?contains(name, 'Pizza')]"
    json: |
       [{
            "name": "Ted's Sub Shop - 720895714701",
            "templateid": "24632"
        },
        {
            "name": "Ted's Pizza - 720895714702",
            "templateid": "24663"
        }]

  tasks:
  - name: DEBUG
    debug:
      msg: "{{ json | from_json | json_query(jq) }}"

It returns the following

ok: [localhost] => {
    "msg": [
        {
            "name": "Ted's Pizza - 720895714702",
            "templateid": "24663"
        }
    ]
}

I need to take it a few steps further and when the value of name contains Pizza I need it to return just the 12 digit number on the end. So the return output would look like this

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

Thoughts?

like image 346
pizzaguy39 Avatar asked Sep 15 '25 13:09

pizzaguy39


1 Answers

you could try

- name: testplaybook jinja2
  hosts: localhost
  gather_facts: no
  vars:
    json: |
       [{
            "name": "Ted's Sub Shop - 720895714701",
            "templateid": "24632"
        },
        {
            "name": "Ted's Pizza - 720895714702",
            "templateid": "24663"
        }]
  tasks:
    - name: DEBUG
      debug:
        msg: "{{ json | from_json | selectattr('name', 'contains' , 'Pizza') 
                                  | map(attribute='name') 
                                  | map('regex_replace', '^.*?(\\d*)$', '\\1')}}" 

result:

ok: [localhost] => {
    "msg": [
        "720895714702"
    ]
}
like image 62
Frenchy Avatar answered Sep 18 '25 09:09

Frenchy