How to iterate over JSON array with jq?

Viewed 7335

I'm building a script to download all CodeCommit repositories at once.

REPOS=$(aws codecommit list-repositories)

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

In first line I get all repos JSON like this:

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

I need simple iterate this json, to get attributes repositoryName and execute git clone for each repository.

But in this example the command jq -r '.[]' don't works.... This return the entire json on each repeat.

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

Output:

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

Or without quotes:

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

Output:

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

I found the problem..... this command:

REPOS=$(aws codecommit list-repositories)

Returns a json like this:

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

I wasn't considering the 'repositories' field in jq.....

This script works fine now:

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

Thank you for support. Have a good day :)

Related