Ask Your Question

Revision history [back]

You can use the following ansible playbook to extract information from a text file and transform it into JSON format:

---
- name: Extract information from text file and transform to JSON format
  hosts: localhost
  vars:
    text_file: "path/to/text_file.txt"
    json_file: "path/to/json_file.json"
  tasks:
    - name: Read text file
      slurp:
        src: "{{ text_file }}"
      register: text_file_data

    - name: Convert text file data to string
      set_fact:
        text_file_string: "{{ text_file_data['content'] | b64decode }}"

    - name: Transform text to JSON
      set_fact:
        json_data: "{{ text_file_string | regex_replace('(\\r\\n)|(\\n\\r)|\\r|\\n', '') | from_json }}"

    - name: Write JSON data to file
      copy:
        content: "{{ json_data | to_nice_json }}"
        dest: "{{ json_file }}"

In this playbook, we first use the slurp module to read the contents of the text file into a variable named text_file_data. We then use the b64decode filter to decode the contents of the file, since the slurp module returns base64-encoded data.

We use the set_fact module to store the decoded file contents as a string in a variable named text_file_string. We then use the regex_replace filter to remove any newline characters from the string, since they can cause issues when converting the string to JSON.

Finally, we use the from_json filter to convert the string to JSON format and store it in a variable named json_data. We use the to_nice_json filter to format the JSON data in a human-readable way, and then write it to a file using the copy module.