1

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]
}
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
Roka
  • 444
  • 5
  • 23
  • 1
    Maybe you can use filter() ? – Aryan Arora May 12 '22 at 21:28
  • 3
    in Python, you can just check individually like `if not something` or more explicitly `if len(something) == 0` or perhaps use `filter()` while iterating, but this is _not_ valid JSON – ti7 May 12 '22 at 21:28
  • 4
    As far as Python is concerned, there are not really such things as "json objects", "json elements" etc. Once you have loaded the data using a JSON library (including the built-in standard library `json`), the data structure that you have is *just* a nested data structure of *perfectly ordinary* Python `dict`s and `list`s, that you can and should process *exactly the same way* that you would if you had gotten that data *in any other way*. – Karl Knechtel May 12 '22 at 21:37
  • 1
    Therefore, you can equivalently ask: "I have a dictionary. How can I easily check whether any of the values is a non-empty list?" And to answer that, first we think of the most straightforward possible approach (which we can identify by breaking the task down into steps: can you check whether a given key is a list? Can you check whether a list is empty? Can you apply a given bit of logic to each value of a dictionary?), and then try to write the code; if the result is not satisfactory, then we can ask a more specific question of ourselves. – Karl Knechtel May 12 '22 at 21:38

2 Answers2

5

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
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
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]
A. K.
  • 34,395
  • 15
  • 52
  • 89