Score:0

How to know a JSON array is an empty array in bash?

cn flag

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?

Score:3
us flag

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
hr flag
... there's also an explicit [isempty](https://jqlang.github.io/jq/manual/#isempty) function
Score:2
my flag

You could test with the array length:

if [[ $(jq length <<<"$Response") -eq 0 ]]; then
    echo "Empty"
else
    echo "Not empty"
fi
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.