Skip to content

Instantly share code, notes, and snippets.

@p4tin
Created October 3, 2020 15:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save p4tin/a49f75457ed02697cf9fe6c16314dc45 to your computer and use it in GitHub Desktop.
Save p4tin/a49f75457ed02697cf9fe6c16314dc45 to your computer and use it in GitHub Desktop.
Json Encode/Decode Python classes
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