In below yaml, I want to iterate through the states and capture both key, value to create associative arrays for each state and then print them.
Note: I'm using yq from mikefarah repo.
data.yaml
data:
continent:
countries:
- state1:
capital1: city1
capital2: city2
- state2:
capital2: city2
- state3:
capital3: city3
- state4:
capital4: city4
capital5: city5
Expected output:
echo state1[@]
key capital1, value city1
key capital2, value city2
echo state2[@]
key capital2, value city2
and so on
I tried multiple ways but unable to traverse each state and capture to array
Try1
#!/bin/bash
declare -A state1_list
while IFS="=" read -r key value; do state1_list["$key"]=$value; done < <(
yq '.mft.aw-dev.components[].state1 | to_entries | map([.key, .value] | join("=")) | .[]' data.yaml
)
for key in "${!state1_list[@]}"; do printf "key %s, value %s\n" "$key" "${state1_list[$key]}"; done
Try2
for i in $(yq '.data.continent.countries[] | keys' data.yaml| sed -e 's/-//g' | sed '/^$/d'); do echo -- $i --; yq '.mft.aw-dev.components[].$i.state[]' data.yaml; done
(For iterating and then finding values)
TIA