'Any array in JSON object is not empty
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]
}
Solution 1:[1]
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
Solution 2:[2]
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]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | BrokenBenchmark |
Solution 2 | A. K. |