如何防止 Ansible 重新排序 JSON? [英] How to prevent Ansible from re-ordering JSON?

查看:14
本文介绍了如何防止 Ansible 重新排序 JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于以下剧本从一些随机的网络服务中获取一些数据:

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 正在重新排序 json 输出:

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": "Sincere@april.biz",
        "id": 1,
        "name": "Leanne Graham",
        "phone": "1-770-736-8031 x56442",
        "username": "Bret",
        "website": "hildegard.org"
    },

而原始数据是:

 {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "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"
    }
  }

如何获得未重新排序的漂亮的格式化 JSON?(我看过这个问题,如果可以的话还是很好的)

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 )

推荐答案

result.content 的值不会被 Ansible 改变并匹配 API 响应.

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

但是当你使用 {{ result.content }} 来显示值时,你触发了 Ansible 类型检测机制,将 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.

这篇关于如何防止 Ansible 重新排序 JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆