HiveBrain v1.2.0
Get Started
← Back to all entries
snippetMinor

How to loop through json without an array

Submitted by: @import:stackexchange-devops··
0
Viewed 0 times
withouthowarrayloopthroughjson

Problem

I am trying to work out how to iterate over some JSON that has repeated structures but have not used a list.

I am using the ansible.posix.firewalld_info module and it returns a dictionary for each zone:

```
{
"active_zones": true,
"changed": false,
"collected_zones": [
"public",
"work"
],
"firewalld_info": {
"default_zone": "public",
"version": "0.9.3",
"zones": {
"public": {
"forward": false,
"forward_ports": [],
"icmp_block_inversion": false,
"icmp_blocks": [],
"interfaces": [
"ens22",
"ens20",
"ens19",
"ens18"
],
"masquerade": true,
"ports": [
[
"9090",
"tcp"
]
],
"protocols": [],
"rich_rules": [],
"services": [
"ssh",
"cockpit",
"MyCustomService"
],
"source_ports": [],
"sources": [],
"target": "DROP"
},
"work": {
"forward": false,
"forward_ports": [],
"icmp_block_inversion": false,
"icmp_blocks": [],
"interfaces": [
"ens21"
],
"masquerade": false,
"ports": [],
"protocols": [],
"rich_rules": [],
"services": [
"ssh",
"dhcpv6-client",
"cockpit"
],
"source_ports": [],
"sources": [],
"target": "default"
}
}
},
"invocation": {
"module_args": {

Solution

Q: "How can I iterate over each zone?"

A: Convert the dictionary to a list, .e.g. given the data in the variable result
- debug:
var: item
loop: "{{ result.firewalld_info.zones.public|dict2items }}"


gives (abridged)
item:
key: forward
value: false

item:
key: forward_ports
value: []

item:
key: icmp_block_inversion
value: false

...


See with_dict

Context

StackExchange DevOps Q#15073, answer score: 4

Revisions (0)

No revisions yet.