简体   繁体   中英

Detect empty json values

I'm trying to detect when I get all empty json values.

Here are 2 examples of empty json values.

json='{
  "data": [],
  "pagination": {
    "cursor": ""
  }
}'

json='{
    "data": [],
    "error": "",
    "message": "",
    "status": ""
}'

The closest I've gotten is this, which seems to work for the first example, but not the 2nd.

echo "$channel_json" | jq -e 'all( .[] ; . == "" or . == [] or . == {}  )'

One, I thought easy way, would be to get the string text from each key pair, then just check if I'm left with an empty string. But I haven't found a way that works in the pagination example.

This will give you false if all strings and arrays are "" or [] :

jq -e 'all(.. | strings, arrays; IN("", [])) | not'

Demo

This might be a good use for gron

json='{
  "data": [],
  "pagination": {
    "cursor": "",
    "position":[2,3]
  }
}'

gron transforms the input JSON into discrete paths:

$ gron <<< "$json"
json = {};
json.data = [];
json.pagination = {};
json.pagination.cursor = "";
json.pagination.position = [];
json.pagination.position[0] = 2;
json.pagination.position[1] = 3;

and to test for any non-empty elements

$ gron <<< "$json" | grep -Evq '(\{\}|\[\]|"");$' && echo "not everything is empty"
not everything is empty

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM