否输出应该像:
country:India, city:India1
country:India, city:India2
country:India, city:India3
country:USA, city:USA1
country:USA, city:USA2
country:USA, city:USA3
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"]
,但我无法获得上面提到的extired outpution
可以在JQ中完全完成此操作。
jq -r '
.countries |
map(
.country as $country |
.city | map("country: \( $country ), city: \( . )\n") | add
) |
join("\n")
'
Gives:
country: India, city: India1
country: India, city: India2
country: India, city: India3
country: USA, city: USA1
country: USA, city: USA2
country: USA, city: USA3
如果您不需要那条空白,那就简单得多。
jq -r '
.countries[] |
.country as $country |
.city[] |
"country: \( $country ), city: \( . )"
'
jqplay如果是不可用的,而Shell脚本确实是唯一的工具,那么我建议使用两阶段的策略。在
阶段中,将JSON转换为某种格式,许多Shell工具可以轻松处理这些格式:这将为我们提供更多用于实现
秒阶段的选择。 具体地,在这种情况下,jq
sed '/city/! d; s/[^[:alnum:]]/ /g' country.json \
| awk '{for (i=4;i<=NF;i++) print $1 ": " $2 ", " $3 ": " $i; print ""}'
sed '/city/! d; s/[^[:alnum:]]/ /g' country.json
----删除其中没有“/city/! d
”的所有行。
city
----用空间替换每个非alphanumeric字符。
recult是
s/[^[:alnum:]]/ /g
! 许多外壳工具可以轻松处理这种格式。其中,
壳(bash或ksh或zsh或...)本身
country India city India1 India2 India3
country USA city USA1 USA2 USA3
,cut
,sort
join
,comm
,
column
awk
awk
:awk '{for (i=4;i<=NF;i++) print $1 ": " $2 ", " $3 ": " $i; print ""}'
llet的分解:
for (i=4;i<=NF;i++)
$1
$2
----第二场
$i
---------------
city
在每个
$city_array
$countryObj
,然后
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