-1

Below is my string value in Jinja2 and Ansible

studId=ValueA,studName=valueB;studId=ValueC,studName=ValueD

Can I change it to dictionary so i can use my jinja2 template as below

student id=item.studId
student name= item.studName

Output expected is

student id=ValueA
student name= ValueB
student id=ValueC
student name= ValueD
josh
  • 11
  • 4
  • Your expected output contains duplicate keys, which cannot be the contents of a dict. – Vijesh Oct 18 '21 at 17:33
  • 1
    You could use split to get a list, and then split the elements again...https://stackoverflow.com/questions/30515456/split-string-into-list-in-jinja – Oliver Gaida Oct 18 '21 at 18:27
  • I have tried earlier. The list it state does not support split method – josh Oct 19 '21 at 01:42

1 Answers1

0

Given the string

    s1: studId=ValueA,studName=valueB;studId=ValueC,studName=ValueD

unify the separators, e.g.

    - set_fact:
        s2: "{{ s1|regex_replace('[,;]', ';') }}"

gives

    s2: studId=ValueA;studName=valueB;studId=ValueC;studName=ValueD

Split the items, iterate them by 2 items, and create the list of the dictionaries, e.g.

    - set_fact:
        l1: "{{ l1|d([]) + [dict(item|map('split', '='))] }}"
      loop: "{{ s2.split(';')|batch(2) }}"

gives the expected structure of the data

  l1:
  - studId: ValueA
    studName: valueB
  - studId: ValueC
    studName: ValueD

Now, the template

    - debug:
        msg: |
          {% for item in l1 %}
          student id={{ item.studId }}
          student name={{ item.studName }}
          {% endfor %}

gives the expected result

  msg: |-
    student id=ValueA
    student name=valueB
    student id=ValueC
    student name=ValueD
Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63
  • this can be done for more thank 1 list sir. fo now i show 2, cn it be done more than 2. can it done in jinja2 template – josh Oct 19 '21 at 11:45