Score:1

Append JSON dictonaries

cn flag

I am using ansible 2.9 and cannot lookout for a way to append below JSON structure with data

"Variables":[
    {
        "Strings": [
            "abc",
            "xyz"
        ],
        "Inputs": true
    }
]

I want to add 'efg' in strings, but not sure what is the syntax to be used in this. using Ansible set_fact for appending this.

I know we can do this using combine_filter but that only works for ansible 2.10 I guess. Any suggestion on how to do this.

br flag
``Variables`` is a list. Do you want to modify only the first item of the list (atm the only one), or do you want to modify any other item in the list as well, if applicable?
AniK avatar
cn flag
I just want to append a new data to Strings, rest all should be as it is. don't want to alter any other content in this.
Michael Hampton avatar
cz flag
Do you mean that you only want to change the _first_ `Strings` list, and do not change any additional `Strings` lists that are added later?
AniK avatar
cn flag
got the answer to above, i meant to add only in Strings list and rest everything should be intact.
Score:0
br flag

You can use combine filter in 2.9. It's been in Ansible since 2.3. What you can't use in 2.9 is the option list_merge. In this case, you can iterate the list and merge the lists on your own, e.g. the play

- hosts: localhost
  vars:
    to_add: efg
    Variables:
      - Strings: [abc, xyz]
        Inputs: true
  tasks:
    - set_fact:
        V2: "{{ V2|d([]) + [item|combine({'Strings': _Strings})] }}"
      loop: "{{ Variables }}"
      vars:
        _Strings: "{{ item.Strings + [to_add] }}"
    - set_fact:
        Variables: "{{ V2 }}"
    - debug:
        var: Variables

does the job

  Variables:
  - Inputs: true
    Strings:
    - abc
    - xyz
    - efg
AniK avatar
cn flag
this was what i was looking for, thank you so much :)
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.