Last active
August 29, 2015 14:01
-
-
Save sangheestyle/ef1d821ef5e69b85a01e to your computer and use it in GitHub Desktop.
Python: convert class into json without None
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 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result