Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save chaudharisuresh997/6c45cf2da41463f4bf38d86d61e0915f to your computer and use it in GitHub Desktop.
Save chaudharisuresh997/6c45cf2da41463f4bf38d86d61e0915f to your computer and use it in GitHub Desktop.
python json to object and object to json
#https://pynative.com/python-convert-json-data-into-custom-python-object/#:~:text=To%20convert%20JSON%20into%20a,into%20a%20custom%20Python%20type.
#https://www.geeksforgeeks.org/encoding-and-decoding-custom-objects-in-python-json/
import json
from json import JSONEncoder
from collections import namedtuple
class Student:
def __init__(self, name, roll_no, address):
self.name = name
self.roll_no = roll_no
self.address = address
class Address:
def __init__(self, city, street, pin):
self.city = city
self.street = street
self.pin = pin
class EncodeStudent(JSONEncoder):
def default(self, o):
return o.__dict__
def customStudentDecoder(studentDict):
return namedtuple('X', studentDict.keys())(*studentDict.values())
address = Address("Bulandshahr", "Adarsh Nagar", "203001")
address2 = Address("Bulandshahr", "Adarsh Nagar", "203001")
adlist=[]
adlist.append(address)
adlist.append(address2)
student = Student("Raju", 53, adlist)
# Encoding custom object to json
# using cls(class) argument of
# dumps method
student_JSON = json.dumps(student, indent = 4,
cls = EncodeStudent)
print(student_JSON)
print(type(student_JSON))
print()
#print(student["roll_no"])
print(type(student))
# Parse JSON into an object with attributes corresponding to dict keys.
studObj = json.loads(student_JSON, object_hook=customStudentDecoder)
print("After Converting JSON Data into Custom Python Object")
print(studObj.address)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment