Skip to content

Instantly share code, notes, and snippets.

@sungitly
Created January 26, 2015 16:00
Show Gist options
  • Save sungitly/a38e971a55c183d1109a to your computer and use it in GitHub Desktop.
Save sungitly/a38e971a55c183d1109a to your computer and use it in GitHub Desktop.
python json encoder to encode object json with exclusions
class ComplexEncoder(json.JSONEncoder):
def __init__(self, skipkeys=False, ensure_ascii=True,
check_circular=True, allow_nan=True, sort_keys=False,
indent=None, separators=None, encoding='utf-8', default=None, excluded=None):
super(ComplexEncoder, self).__init__(skipkeys, ensure_ascii, check_circular, allow_nan, sort_keys, indent,
separators, encoding, default)
self.excluded = excluded
def default(self, obj):
if hasattr(obj, "__dict__"):
data = dict([(key, value)
for key, value in obj.__dict__.iteritems()
if not callable(value) and not key.startswith('_') and key not in self.excluded])
return data
# Let the base class default method raise the TypeError
return json.JSONEncoder.default(self, obj)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment