frazman
frazman

Reputation: 33223

parsing json to check whether a field is blank in bash

So, lets say, I am trying to write a shell script which does the following:

1) Ping http://localhost:8088/query?key=q1
2) It returns a json response :
    {
"status": "success", 
"result": []
 "query": "q1"
  }
or
{
"status": "success", 
"result": ["foo"], 
"artist_key": "q1"

}

The "result" is either an empty array or filled array.. I am trying to write a shell script which is checking whether "result" is empty list or not?

Upvotes: 1

Views: 5676

Answers (2)

zerodiff
zerodiff

Reputation: 1700

Something like this would work:

# Assume result is from curl, but could be in a file or whatever
if curl "http://localhost:8088/query?key=q1" | grep -Pq '"result":\s+\[".+"\]'; then
    echo "has result"
else
    echo "does not have result"
fi

However, I'm assuming these are on separate lines. If not, there are linters for format it.

Edited (based on the jq comment), here's a jq solution as suggested by Adrian Frühwirth:

result=$( curl "http://localhost:8088/query?key=q1" | jq '.result' )
if [ "$result" == "[]" ]; then
    echo "does not have result"
else
    echo "has result"
fi

I have learned something new today. And as I play around with this more, maybe it's better to do this:

result=$( curl "http://localhost:8088/query?key=q1" | jq '.result | has(0)' )
if [ "$result" == "true" ]; then
    echo "has result"
else
    echo "does not have result"
fi

See the manual. I wasn't able to get the -e or --exit-status arguments to work.

Upvotes: 4

glenn jackman
glenn jackman

Reputation: 246764

I'd use a language that can convert JSON to a native data structure:

wget -O- "http://localhost:8088/query?key=q1" |
perl -MJSON -0777 -ne '
    $data = decode_json $_;
    exit (@{$data->{result}} == 0)
'

That exits with a success status if the result attribute is NOT empty. Encapsulating into a shell function:

check_result() {
    wget -O- "http://localhost:8088/query?key=q1" |
    perl -MJSON -0777 -ne '$data = decode_json $_; exit (@{$data->{result}} == 0)'
}

if check_result; then 
    echo result is NOT empty
else
    echo result is EMPTY
fi

I like ruby for parsing JSON:

ruby -rjson -e 'data = JSON.parse(STDIN.read); exit (data["result"].length > 0)'

It's interesting that the exit status requires the opposite comparison operator. I guess ruby will convert exit(true) to exit(0), unlike perl which has no true boolean objects only integers.

Upvotes: 2

Related Questions