Created
May 6, 2014 05:00
-
-
Save kalharbi/56dd376fe49c47d9b9be to your computer and use it in GitHub Desktop.
A custom JSON encoder that excludes null or empty pair values.
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
from json import JSONEncoder | |
class CustomJsonEncoder(JSONEncoder): | |
def remove_none(self, data): | |
if isinstance(data, dict): | |
return {k:self.remove_none(v) for k, v in data.items() if k and v } | |
elif isinstance(data, list): | |
return [self.remove_none(item) for item in data if item] | |
elif isinstance(data, set): | |
return {self.remove_none(item) for item in data if item} | |
else: | |
return data | |
def default(self, obj): | |
return self.remove_none(obj.__dict__) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: