Created
October 3, 2020 15:17
-
-
Save p4tin/a49f75457ed02697cf9fe6c16314dc45 to your computer and use it in GitHub Desktop.
Json Encode/Decode Python classes
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 | |
from json import JSONEncoder | |
class Student: | |
def __init__(self, first_name, last_name): | |
self._first_name = first_name | |
self._last_name = last_name | |
@property | |
def first_name(self): | |
return self._first_name | |
@property | |
def last_name(self): | |
return self._last_name | |
@property | |
def name(self): | |
return f"{self._first_name} {self._last_name}" | |
# subclass JSONEncoder | |
class StudentEncoder(JSONEncoder): | |
def default(self, o): | |
d = o.__dict__ | |
new_dict = {} | |
for k, v in d.items(): | |
if k.startswith("_"): | |
k = k[1:] | |
new_dict[k] = v | |
return new_dict | |
student1 = Student("Paul", "fortin") | |
print(student1) | |
studentJSONData = json.dumps(student1, indent=4, cls=StudentEncoder) | |
print(studentJSONData) | |
from_json = json.loads(studentJSONData) | |
print(from_json) | |
student2 = Student(from_json.get("first_name"), from_json.get("last_name")) | |
print(student2.name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment