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 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)} |
thanks for you useful solution
Thank you , elegant solution !
thank you!
thank you !!!
I needed a function to remove all keys with (values == "") from a very large, very nested JSON, and changing a little bit the function empty() worked flawlessly.
def empty(x):
return x is None or x == {} or x == [] or x == ""
thanks sm worked marvellously
Build a small tool if you need to simplify your config, or similar: https://simplifyjson.com
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you 🙏