Skip to content

Instantly share code, notes, and snippets.

@nlohmann
Created March 12, 2018 14:19
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save nlohmann/c899442d8126917946580e7f84bf7ee7 to your computer and use it in GitHub Desktop.
Save nlohmann/c899442d8126917946580e7f84bf7ee7 to your computer and use it in GitHub Desktop.
Remove empty arrays, objects or null elements from a JSON value
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)}
@burakhanaksoy
Copy link

Thank you 🙏

@kernel-loophole
Copy link

thanks for you useful solution

@espinraf
Copy link

Thank you , elegant solution !

@liuwenjie
Copy link

thank you!

@rnapoli
Copy link

rnapoli commented Oct 19, 2022

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 == ""

@katienoel1
Copy link

katienoel1 commented Jul 20, 2023

thanks sm worked marvellously

@buger
Copy link

buger commented Jul 22, 2023

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