我正在尝试使用shell脚本解析下面的json对象:
country.json
{
"countries": [
{"country":"India","city":["India1","India2","India3"]},
{"country":"USA","city":["USA1","USA2","USA3"]}
]
}
并且我的期望输出应该是:
country:India, city:India1
country:India, city:India2
country:India, city:India3
country:USA, city:USA1
country:USA, city:USA2
country:USA, city:USA3
我在shell脚本中使用jq来迭代上面的json,如下所示:
for k in $(jq '.countries | keys | .[]' country.json); do
countryObj=$(jq -r ".countries[$k]" country.json);
countryValue=$(jq -r '.country' <<< "$countryObj");
city_array=$(jq -r '.city' <<< "$countryObj");
echo $city_array
done
由此,我可以获得city_array,即["India1","India2","India3"]
和["USA1","USA2","USA3"]
,但我无法获得上述所需的输出
这完全可以在jq中完成。
jq -r '
.countries |
map(
.country as $country |
.city | map("country: ( $country ), city: ( . )n") | add
) |
join("n")
'
提供:
country: India, city: India1
country: India, city: India2
country: India, city: India3
country: USA, city: USA1
country: USA, city: USA2
country: USA, city: USA3
jqplay
如果你不需要空白行,它会简单得多。
jq -r '
.countries[] |
.country as $country |
.city[] |
"country: ( $country ), city: ( . )"
'
jqplay
添加一个循环,为每个$countryObj
迭代$city_array
中的每个city
,然后逐行迭代echo
您想要的输出。
for k in $(jq '.countries | keys | .[]' country.json); do
countryObj=$(jq -r ".countries[$k]" country.json);
countryValue=$(jq -r '.country' <<< "$countryObj");
city_array=$(jq -r '.city' <<< "$countryObj");
for city in $city_array; do
echo "country:$countryValue, city:$city"
done
echo "" # Blank line between each country
done