3

I use this code to consume GitHub API and automate some tasks:

curl --silent -H 'Authorization: token github_access_token' 'https://api.github.com/orgs/OrganizationName/repos?per_page=100'

Sometimes I get this as the response:

[

]

I want to know if the response is an empty array or not.

I thought of using jq like echo $Response | jq -r ".[]" but I don't know how to continue from there.

How can I find out a JSON string is an empty array in bash?

muru
  • 207,228

2 Answers2

6

If you jq, you can test whether the input is an empty list:

% echo '["a"]' | jq '. == []'
false
% echo '[]' | jq '. == []'
true
% echo '[]' | jq -e '. | length == 0'
true
% echo '["a"]' | jq -e '. | length == 0'
false

And you can use the -e option:

--exit-status / -e:

Sets the exit status of jq to 0 if the last output value was neither false nor null, 1 if the last output value was either false or null, or 4 if no valid result was ever produced. Normally jq exits with 2 if there was any usage problem or system error, 3 if there was a jq program compile error, or 0 if the jq program ran.

So:

if curl --silent -H 'Authorization: token github_access_token' 'https://api.github.com/orgs/OrganizationName/repos?per_page=100' |
   jq -e '. == []'
then
  echo Empty output
else
  echo Got something
fi
muru
  • 207,228
3

You could test with the array length:

if [[ $(jq length <<<"$Response") -eq 0 ]]; then
    echo "Empty"
else
    echo "Not empty"
fi