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]
}
4
  • 1
    Maybe you can use filter() ? Commented May 12, 2022 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 Commented May 12, 2022 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 dicts and lists, that you can and should process exactly the same way that you would if you had gotten that data in any other way. Commented May 12, 2022 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. Commented May 12, 2022 at 21:38

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.