[英]Ansible Convert JSON to dictionary
我有一個 HTTP 端點,它返回一個 JSON。 格式如下:
[
{
"abbreviation_id": 1,
"FullName": "Tiger",
"abbreviation": "tig",
"active": true,
"createdDate": "2021-01-25T06:17:32",
"modifiedDate": "2021-01-25T06:17:32"
},
{
"abbreviation_id": 69,
"FullName": "Jaguar",
"abbreviation": "jag",
"active": true,
"createdDate": "2021-01-25T06:17:32",
"modifiedDate": "2021-01-25T06:17:32"
}
]
檢索到這個之后,我有一個名為 {{ AnName }} 的變量,我需要從 JSON 中找到它的等效縮寫。 我整天都在搜索如何做到這一點,所以我嘗試使用以下代碼對其進行查詢:
- name: Get abbreviation
debug:
var: item
loop: "{{ animal_lookups | community.general.json_query(abbreviation_query) }}"
vars:
abbreviation_query: "animal_lookups[?FullName == {{
AnName }}].abbreviation"
但我意識到我還沒有安裝community.general。 這讓我問這是否是最好的方法,或者有沒有辦法讓我將 JSON 轉換為字典,以便我可以做 animal_lookups.AnName。 希望是這樣的:
animal_lookups:
Tiger: tig
Jaguar: jag
太感謝了!
更新:: 嘗試了弗拉基米爾的解決方案,但似乎我的 animal_lookups 被識別為字典,而不是 JSON。
此代碼片段顯示 HTTP 調用,該調用返回 JSON(如下所示),並且該任務應轉換為字典。
- name: Get Abbreviations
uri:
url: "https://{{ function_name }}.azurewebsites.net/api/ListAnimals?code={{ function_code }}"
method: "GET"
return_content: yes
timeout: 60
body_format: json
register: animal_lookups
no_log: "{{ secure_logging }}"
- name: Convert JSON to dict
set_fact:
animal_dict: "{{ animal_lookups|
items2dict(key_name='FullName',
value_name='abbreviation') }}"
在日志中,它返回 JSON:
"json": [
{
"abbreviation": "tig",
"active": true,
"cdl_abbreviation_id": 68,
"createdDate": "2021-01-25T06:17:32",
"digitalSolution": "Tiger",
"modifiedDate": "2021-01-25T06:17:32"
},
{
"abbreviation": "jag",
"active": true,
"cdl_abbreviation_id": 69,
"createdDate": "2021-01-25T06:17:32",
"digitalSolution": "Jaguar",
"modifiedDate": "2021-01-25T06:17:32"
}
]
但返回錯誤:
"msg": "items2dict requires a list, got <class 'dict'> instead."
這個問題已經在這里得到了部分回答,但是自從 Ansible 2.9 和 collections 的興起以來,我認為在這里再次回答它會很有用。
如果我正確理解您的問題,您想從動物列表中找到給定FullName
的動物的縮寫。
我能想到的最好方法是使用community.general
集合中的json_query
。
為了安全起見,我建議在對變量AnName
運行測試之前測試 object 上是否存在鍵FullName
。 此外,添加第first
過濾器以獲得結果的第一個值。 默認情況下, json_query
返回一個列表。
這是我制作的示例playbooks
,其中包括我提到的所有內容:
- hosts: localhost
gather_facts: no
tasks:
- name: Load JSON file
set_fact:
animal_lookups: "{{ lookup('file', 'animal_lookups.json') | from_json }}"
- debug:
var: animal_lookups
- debug:
msg: "{{ animal_lookups | community.general.json_query(query) | first }}"
vars:
animal_name: Tiger
query: "[?FullName == '{{ animal_name }}'].abbreviation"
為了簡化測試,我從文件中加載 Animal 集合,然后運行查詢,如圖所示。 如果要將結果保存在另一個變量上,可以使用set_fact
模塊而不是debug
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.