【问题标题】:How to prevent Ansible from re-ordering JSON?如何防止 Ansible 重新排序 JSON?
【发布时间】:2017-09-06 11:15:23
【问题描述】:

鉴于以下剧本从一些随机的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 输出:

输出(数组的第一个元素,重新排序):

    {
        "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? (我看过this question,如果可以的话还是不错的)

【问题讨论】:

    标签: json ansible


    【解决方案1】:

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

    您可以轻松地测试它:

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

    但是当你使用{{ result.content }}显示值时,会触发Ansible类型检测机制,将JSON字符串转换为对象(无序),然后打印对象的值(不是原始值)。

    为了防止类型检测,您可以使用| string 过滤器。

    有关更多详细信息,另请参阅this answer

    【讨论】:

      猜你喜欢
      • 2019-06-19
      • 2013-07-08
      • 1970-01-01
      • 1970-01-01
      • 2020-12-02
      • 2013-03-21
      • 2012-01-11
      • 2013-09-11
      • 1970-01-01
      相关资源
      最近更新 更多