Home > Back-end >  separate json keys into different file ansible
separate json keys into different file ansible

Time:03-27

I have a variable of a large JSON data of students' data of different classes containing their names and numbers respectively. The variable is "data" and here is what the variable contains:

{
"Class001": [
    {
        "Jesse": 001
    },
    {
        "Adam": 002
    }
],
"Class002": [
    {
        "Jill": 111
    },
    {
        "Ray": 112
    }
],
.....
}

Using ansible, I want to separate the keys "Class00X" into some different files. For example, the Class001 file contain:

    {
        "Jesse": 001
    },
    {
        "Adam": 002
    },
    .....

etc. How can i do this? thanks

CodePudding user response:

i have created a file.json with:

{
  "Class001": [
      {
          "Jesse": "001"
      },
      {
          "Adam": "002"
      }
  ],
  "Class002": [
      {
          "Jill": "111"
      },
      {
          "Ray": "112"
      }
  ]
  }

this playbook does the job:

- hosts: localhost
  gather_facts: no
  vars:
    json: "{{ lookup('file', 'file.json') | from_json }}"
  tasks:
    - name: loop
      copy:
        dest: "files/{{ item.key }}.txt" 
        content: "{{ item.value | to_nice_json }}"       
      loop: "{{ json | dict2items }}"

here files files/class001.txt and files/class002.txt are created

CodePudding user response:

A dictionary is a better structure to store students' names and numbers. Optionally, store the dictionaries instead of lists

    - copy:
        dest: "files/{{ item.key }}.yml"
        content: "{{ item.value|combine|to_nice_yaml }}"
      loop: "{{ json|dict2items }}"

gives

shell> cat files/Class001.yml 
Adam: '002'
Jesse: '001'
shell> cat files/Class002.yml 
Jill: '111'
Ray: '112
  • Related