2017-09-06 125 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瞭解更多詳情。