Home > Mobile >  Any array in JSON object is not empty
Any array in JSON object is not empty

Time:05-13

Is there a clever way to check if any array in a JSON element is not empty? Here is example data:

{
  a = []
  b = []
  c = [1,2,3]
}

CodePudding user response:

You can use any(), returning True if any of the values in the JSON object are truthy:

data = {
  'a': [],
  'b': [],
  'c': [1,2,3]
}

result = any(item for item in data.values())

print(result)

This outputs:

True

CodePudding user response:

Empty lists are Falsy so you can check for the Truthness of value against each key. e.g.,

>>> a = json.loads('{"a" : [], "b" : [], "c" : [1,2,3]}')
>>> for i,j in a.items():
...     if j:
...             print(j)
... 
[1, 2, 3]
  • Related