我呼叫Web服务,该网络服务返回A json 响应。这是任务:
- name: calls webservice for json
uri:
url: ...
method: GET
body_format: json
register: json_response
这是由称为WebService返回的简化响应:
{
"nodes": {
"hash1": {
"name": "host1"
},
"hash2": {
"name": "host2"
}
}
}
您可以看到,返回响应中的 nodes 是地图。每个条目代表一些主机。钥匙是一些哈希值,对我来说并不重要。我需要检查这些文档中的任何一个中是否包含指定值,例如。&quot" host1"。
如何检查返回的JSON是否包含 name 字段中的指定主机?
您可以使用json_query滤波器使用jmespath幕后的json_query滤镜。
一本简单的有关您问题的剧本看起来像:
---
- hosts: localhost
gather_facts: False
vars:
json_query: "nodes.*[] | [?name=='host1']"
json_response: |
{
"nodes": {
"hash1": {
"name": "host1"
},
"hash2": {
"name": "host2"
}
}
}
tasks:
- name: debug
debug:
msg: "{{ json_response | from_json | json_query(json_query) }}"