Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent Ansible from re-ordering JSON?

Tags:

json

ansible

Given the following playbook fetching some data from some random webservice:

---
- name: sorting json
  hosts: localhost
  tasks:
   - name:
     uri:
       url: http://jsonplaceholder.typicode.com/users
       method: GET
       return_content: yes
     register: result
     ignore_errors: yes


   - debug: msg="{{result.content}}"

Ansible is reordering the json output:

Output (first element of array, reordered):

    {
        "address": {
            "city": "Gwenborough",
            "geo": {
                "lat": "-37.3159",
                "lng": "81.1496"
            },
            "street": "Kulas Light",
            "suite": "Apt. 556",
            "zipcode": "92998-3874"
        },
        "company": {
            "bs": "harness real-time e-markets",
            "catchPhrase": "Multi-layered client-server neural-net",
            "name": "Romaguera-Crona"
        },
        "email": "[email protected]",
        "id": 1,
        "name": "Leanne Graham",
        "phone": "1-770-736-8031 x56442",
        "username": "Bret",
        "website": "hildegard.org"
    },

Whereas the original data is:

 {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "[email protected]",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
    }
  }

How to get a nice, formatted JSON which is not reordered? ( I have seen this question, it would still be nice if it was possible )

like image 277
user140547 Avatar asked Oct 27 '25 04:10

user140547


1 Answers

The value of result.content is not altered by Ansible and matches API response.

You can easily test it with:

- copy:
    content: "{{ result.content | string }}"
    dest: /tmp/raw.json

But when you use {{ result.content }} to display the value, you trigger Ansible type detection mechanism, which converts JSON string into object (which is unordered) and then prints the object's value (not original value).

To prevent type detection, you can use | string filter.

Also see this answer for some more details.

like image 133
Konstantin Suvorov Avatar answered Oct 30 '25 12:10

Konstantin Suvorov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!