Created
March 12, 2018 14:19
-
-
Save nlohmann/c899442d8126917946580e7f84bf7ee7 to your computer and use it in GitHub Desktop.
Remove empty arrays, objects or null elements from a JSON value
This file contains hidden or 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
thanks sm worked marvellously