-
-
Save devsetgo/82ac265868fbb71cbbfdaf04944fb612 to your computer and use it in GitHub Desktop.
Remove empty arrays, objects or null elements from a JSON value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def remove_empty_elements(d): | |
"""recursively remove empty lists, empty dicts, or None elements from a dictionary""" | |
def empty(x): | |
return x is None or x == {} or x == [] | |
if not isinstance(d, (dict, list)): | |
return d | |
elif isinstance(d, list): | |
return [v for v in (remove_empty_elements(v) for v in d) if not empty(v)] | |
else: | |
return {k: v for k, v in ((k, remove_empty_elements(v)) for k, v in d.items()) if not empty(v)} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment