我正在尝试使用Shell脚本在JSON对象下方解析:

问题描述 投票:0回答:2
我的

否输出应该像:

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"]
,但我无法获得上面提到的

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

arrays json bash shell jq
2个回答
6
投票

如果您不需要那条空白,那就简单得多。
jq -r ' .countries[] | .country as $country | .city[] | "country: \( $country ), city: \( . )" '

jqplay

如果是不可用的,而Shell脚本确实是唯一的工具,那么我建议使用两阶段的策略。在
first

阶段中,将JSON转换为某种格式,许多Shell工具可以轻松处理这些格式:这将为我们提供更多用于实现

秒阶段的选择。 具体地,在这种情况下,
jq

第一阶段

sed '/city/! d; s/[^[:alnum:]]/ /g' country.json \ | awk '{for (i=4;i<=NF;i++) print $1 ": " $2 ", " $3 ": " $i; print ""}'

0
投票

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
  • ok,
    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
  • 中,每个to in
  • $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
        
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.