Created
October 27, 2020 14:06
-
-
Save tkallenberg-tw/15529a46b41c7ae305b3c17c77f06c1d to your computer and use it in GitHub Desktop.
Simple python object to json serialization
This file contains 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
import json | |
import pprint | |
class Brain: | |
def __init__(self, iq): | |
self.iq = iq | |
class Person(): | |
def __init__(self, name=None, age=None, brain: Brain=None): | |
self.age = age | |
if brain: | |
self.brain = Brain(**brain) | |
self.name=name | |
def toJSON(self): | |
return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True, indent=4) | |
@classmethod | |
def from_dict(cls, dict): | |
obj = cls() | |
obj.__dict__.update(dict) | |
return obj | |
person_string = '{"name": "Bob", "age": 25, "brain" : { "iq" : "100" }}' | |
person_dict = json.loads(person_string) | |
person_object = Person(**person_dict) | |
pprint.pprint(person_object.name) | |
pprint.pprint(person_object.brain) | |
pprint.pprint(type(person_object.brain)) | |
pprint.pprint(person_object.brain.iq) | |
person_string_2 = person_object.toJSON() | |
ix = json.loads(person_string_2, object_hook=Person.from_dict) | |
pprint.pprint(type(ix.brain)) | |
pprint.pprint(ix.brain.iq) | |
pprint.pprint(ix.name) | |
print("person3") | |
person_string_3 = """ | |
{ | |
"age": 25, | |
"brain": { | |
"iq": "100" | |
}, | |
"name": "Bob", | |
"whatever": 42 | |
} | |
""" | |
ix = json.loads(person_string_3, object_hook=Person.from_dict) | |
pprint.pprint(type(ix.brain)) | |
pprint.pprint(ix.brain.iq) | |
pprint.pprint(ix.name) | |
pprint.pprint(ix.whatever) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment