2017-09-06 93 views
0

给定以下剧本取一些数据从一些随机webservice如何防止Ansible重新排序JSON?

--- 
- 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": "[email protected]", 
     "id": 1, 
     "name": "Leanne Graham", 
     "phone": "1-770-736-8031 x56442", 
     "username": "Bret", 
     "website": "hildegard.org" 
    }, 

鉴于原始数据为:

{ 
    "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" 
    } 
    } 

如何获得一个不重排的格式化好的JSON? (我见过this question,如果可能的话,它仍然会很好)

回答

1

Ansible没有更改result.content的值,并且匹配API响应。

你可以很容易与测试:

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

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

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

另请参阅this answer了解更多详情。