Skip to content

Instantly share code, notes, and snippets.

@sangheestyle
Last active August 29, 2015 14:01
Show Gist options
  • Save sangheestyle/ef1d821ef5e69b85a01e to your computer and use it in GitHub Desktop.
Save sangheestyle/ef1d821ef5e69b85a01e to your computer and use it in GitHub Desktop.
Python: convert class into json without None
from json import JSONEncoder
class MyEncoder(JSONEncoder):
def default(self, o):
temp = o.__dict__
a = dict()
for k, v in temp.iteritems():
if v is not None:
if type(v) is list:
v = [x for x in v if x is not None]
a[k] = v
return a
class Person:
def __init__(self, name, age=None):
self.name = name
self.age = age
sanghee = Person("sanghee", 35)
stranger1 = Person("stranger")
stranger2 = Person(["a", None, "b"])
stranger3 = Person(["a", None, "b"], 21)
print MyEncoder().encode(sanghee)
print MyEncoder().encode(stranger1)
print MyEncoder().encode(stranger2)
print MyEncoder().encode(stranger3)
@sangheestyle
Copy link
Author

Result

{"age": 35, "name": "sanghee"}
{"name": "stranger"}
{"name": ["a", "b"]}
{"age": 21, "name": ["a", "b"]}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment