gau*_*nha 1 arrays bash shell json jq
我正在尝试使用 shell 脚本解析以下 json 对象:
国家.json
{
"countries": [
{"country":"India","city":["India1","India2","India3"]},
{"country":"USA","city":["USA1","USA2","USA3"]}
]
}
Run Code Online (Sandbox Code Playgroud)
我想要的输出应该是:
country:India, city:India1
country:India, city:India2
country:India, city:India3
country:USA, city:USA1
country:USA, city:USA2
country:USA, city:USA3
Run Code Online (Sandbox Code Playgroud)
我在 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
Run Code Online (Sandbox Code Playgroud)
由此我能够获得 city_array ie ["India1","India2","India3"],["USA1","USA2","USA3"]但我无法获得上述所需的输出
这完全可以在 jq 中完成。
jq -r '
.countries |
map(
.country as $country |
.city | map("country: \( $country ), city: \( . )\n") | add
) |
join("\n")
'
Run Code Online (Sandbox Code Playgroud)
给出:
country: India, city: India1
country: India, city: India2
country: India, city: India3
country: USA, city: USA1
country: USA, city: USA2
country: USA, city: USA3
Run Code Online (Sandbox Code Playgroud)
如果你不需要那个空行,那就简单多了。
jq -r '
.countries[] |
.country as $country |
.city[] |
"country: \( $country ), city: \( . )"
'
Run Code Online (Sandbox Code Playgroud)