json parsing using ansible

Viewed 47

Hi, Could someone please help how to sort the below using ansible

"msg": [
    {
        "Desc": "jkl - txt to search-\n",
        "SCTASK": "SCTASK000001"
    },
    {
        "Desc": "xyz - txt to search-\n",
        "SCTASK": "SCTASK000002"
    },
    {
        "Desc": "def - txt to search-\n",
        "SCTASK": "SCTASK000003"
    },
    {
        "Desc": "def - txt to search-\n",
        "SCTASK": "SCTASK000004"
    },
    {
        "Desc": "abc- txt to search-\n",
        "SCTASK": "SCTASK000005"
    }
  ]

I need to get both sctask and description where 'abc' word present in 'Desc'. I tried to use where condition in my code block but it's not filtering.

- set_fact:
    SCT: "{{ jsoncontent.json | json_query(query)}}"
  vars:
    query: "result[*].{Desc: description, SCTASK: number}"

- name: debug
  debug: msg="{{ item }}"
  loop: "{{SCT}}"
  when: SCT is search("abc")

   

Thanks!

1 Answers

Q: "Get both sctask and description where 'abc' word present in 'Desc'."

A: json_query is not needed. Simply use the filter selectattr

    - set_fact:
        SCT: "{{ jsoncontent.json.result|selectattr('Desc', 'search', 'abc') }}"

gives

SCT:
  - Desc: |-
      abc- txt to search-
    SCTASK: SCTASK000005

Notes

  • If you want to select the items in the loop simply iterate the list
    - debug:
        msg: "{{ item }}"
      loop: "{{ jsoncontent.json.result }}"
      when: item.Desc is search("abc")

gives

TASK [debug] *******************************************************************************
skipping: [localhost] => (item={'Desc': 'jkl - txt to search-\n', 'SCTASK': 'SCTASK000001'}) 
skipping: [localhost] => (item={'Desc': 'xyz - txt to search-\n', 'SCTASK': 'SCTASK000002'}) 
skipping: [localhost] => (item={'Desc': 'def - txt to search-\n', 'SCTASK': 'SCTASK000003'}) 
skipping: [localhost] => (item={'Desc': 'def - txt to search-\n', 'SCTASK': 'SCTASK000004'}) 
ok: [localhost] => (item={'Desc': 'abc- txt to search-\n', 'SCTASK': 'SCTASK000005'}) => 
  msg:
    Desc: |-
      abc- txt to search-
    SCTASK: SCTASK000005
  • You can also create the list SCT in a loop. The task below gives the same result.
    - set_fact:
        SCT: "{{ SCT|d([]) + [item] }}"
      loop: "{{ jsoncontent.json.result }}"
      when: item.Desc is search("abc")
Related