如何使用jq迭代JSON数组?

3vpjnl9f  于 2023-06-25  发布在  其他
关注(0)|答案(3)|浏览(143)

我正在构建一个脚本来一次下载所有CodeCommit存储库。

REPOS=$(aws codecommit list-repositories)

echo $REPOS | jq -r '.[]' | while read name ; do
    git clone XXX
done

在第一行中,我得到了所有的repos JSON如下:

[
  {
    "repositoryName": "repo_a",
    "repositoryId": "XXXXXX"
  },
  {
    "repositoryName": "repo_b",
    "repositoryId": "XXXXXX"
  },
  {
    "repositoryName": "repo_c",
    "repositoryId": "XXXXXX"
  },
  {
    "repositoryName": "repo_d",
    "repositoryId": "XXXXXX"
  }
]

我需要简单的迭代这个json,以获得属性repositoryName并为每个仓库执行git clone。
但是在这个例子中,命令jq -r '.[]'不起作用。这会在每次重复时返回整个json。

vsdwdz23

vsdwdz231#

echo "$REPOS" | jq '.[].repositoryName' | while read -r repo; do echo "do something with $repo"; done

输出:

do something with "repo_a"
do something with "repo_b"
do something with "repo_c"
do something with "repo_d"

或者不加引号:

echo "$REPOS" | jq -r '.[].repositoryName' | while read -r repo; do echo "do something with $repo"; done

输出:

do something with repo_a
do something with repo_b
do something with repo_c
do something with repo_d
dz6r00yl

dz6r00yl2#

我发现问题了……此命令:

REPOS=$(aws codecommit list-repositories)

返回一个json,如下所示:

{
  "repositories": [
  {
    "repositoryName": "repo_a",
    "repositoryId": "XXXXXX"
  },
  {
    "repositoryName": "repo_b",
    "repositoryId": "XXXXXX"
  },
  {
    "repositoryName": "repo_c",
    "repositoryId": "XXXXXX"
  },
  {
    "repositoryName": "repo_d",
    "repositoryId": "XXXXXX"
  }
]
}

我没有考虑jq中的“repositories”字段。
这个脚本现在运行良好:

REPOS=$(aws codecommit list-repositories)

echo $REPOS | jq -r '.repositories[].repositoryName' | while read name ; do
    git clone ssh://git-codecommit.us-east-1.amazonaws.com/v1/repos/$name
done

感谢您的支持。祝你有个美好的一天:)

tez616oj

tez616oj3#

如果你想迭代JSON值而不是单个字段值,你可以使用-c选项,这样你就可以每行得到一个JSON元素:

repositories='{
  "repositories": [
  {
    "repositoryName": "repo_a",
    "repositoryId": "XXXXXX"
  },
  {
    "repositoryName": "repo_b",
    "repositoryId": "XXXXXX"
  },
  {
    "repositoryName": "repo_c",
    "repositoryId": "XXXXXX"
  },
  {
    "repositoryName": "repo_d",
    "repositoryId": "XXXXXX"
  }
]
}'
while read repository
do
  name=$(echo "$repository" | jq -r .repositoryName)
  id=$(echo "$repository" | jq -r .repositoryId)

  echo "${id}=${name}"
done < <(echo "$repositories" | jq -c '.repositories[]')

相关问题