[英]Loop through JSON response - Ansible
I have a JSON response from the server that looks like this: 我从服务器收到一个JSON响应,如下所示:
{
"rules": [
{
"id": "1234",
"disabled": false,
"condition": [
"or",
[
"contains",
[
"path",
"payload",
"custom_details",
"resolved"
],
"Platform"
],
[
"contains",
[
"path",
"payload",
"custom_details",
"firing"
],
"Platform"
]
],
"catch_all": false,
"advanced_condition": [],
"actions": [
[
"route",
"XYZ123"
],
[
"extract",
"^\\[.*\\] *([^ ]*)",
[
"path",
"payload",
"summary"
],
"description"
]
]
},
{
"id": "9876",
"disabled": false,
"condition": [
"or",
[
"contains",
[
"path",
"payload",
"custom_details",
"resolved"
],
"Sidewalk"
],
[
"contains",
[
"path",
"payload",
"custom_details",
"firing"
],
"Sidewalk"
]
],
"catch_all": false,
"advanced_condition": [],
"actions": [
[
"route",
"QWERT1"
],
[
"extract",
"^\\[.*\\] *([^ ]*)",
[
"path",
"payload",
"summary"
],
"description"
]
]
}
]
I want to loop over this and match the string Sidewalk
. 我想循环遍历并匹配字符串
Sidewalk
。 If there is a match, then get the value of id
of the matched. 如果存在匹配项,则获取匹配项的
id
的值。
I tried this 我试过了
---
- name: API call - GET Event Rule ID
uri:
url: "{{ api_event_rules }}"
method: GET
status_code: 200
headers:
Content-Type: "application/json"
Accept: "application/vnd.ap+json;version=2"
Authorization: "Token token={{ api_token }}"
register: json_response
I tried this JMESPath 我尝试了这个JMESPath
rules[*].condition[*][2]
But this gives out something like this: 但这给出了这样的内容:
[
[
"Platform",
"Platform"
],
[
"Sidewalk",
"Sidewalk"
],
I'm not able to find my way past this, very new to ansible. 我无法通过这条路,这对ansible很新。 Any help is much appreciated.
任何帮助深表感谢。
Q: "Match the string Sidewalk. If there is a match, then get the value of id of the matched."
问:“匹配字符串Sidewalk。如果存在匹配项,则获取匹配的id的值。”
A: It's not clear which 'Sidewalk' we shall look for. 答:不清楚我们要寻找哪个“人行道”。 Let's take first one.
让我们来第一个。 The task below creates a dictionary of id and the corresponding condition
下面的任务创建一个id和相应条件的字典
- set_fact:
ids: "{{ rules|
json_query('[*].{key: condition[1][2], value: id}')|
items2dict
}}"
- debug:
var: ids['Sidewalk']
The debug gives 调试给出
"ids['Sidewalk']": "9876"
If this shall be a conditional task the debug below 如果这是一个有条件的任务,请在下面进行调试
- debug:
msg: "Sidewalk found with id: {{ ids['Sidewalk'] }}"
when: "'Sidewalk' in ids.keys()"
gives 给
"msg": "Sidewalk found with id: 9876"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.