I’ve recently had a need to convert some python classes to json in order to send data via an API. Here’s a simple example to show how to convert a class of students to a json array of students. This was with the help of the following links: LINK, LINK.
For a quick overview, we pull in the raw student data, create Student objects that are appended to a student array, and then the student array is then used to create a Students class. We then serialize the students class.
import json
class Student:
def __init__(self, student_id, first_name, last_name, grade_level):
self.student_id = student_id
self.first_name = first_name
self.last_name = last_name
self.grade_level = grade_level
class Students:
def __init__(self, students):
self.students = students
# ID, First Name, Last Name, Grade Level
raw_student_data = [['336', 'John', 'Xiong', 8]
, ['824', 'Ifa', 'Suibne', 4]
, ['992', 'Gobannos', 'Tadhg', 6]
, ['124', 'Mukhtaar', 'Onyekachi', 12]]
student_array = []
for row in raw_student_data:
student_array.append(Student(row[0], row[1], row[2], row[3]))
students = Students(student_array)
print(json.dumps(students.__dict__, default=lambda o: o.__dict__))
Output:
{“students”: [{“student_id”: “336”, “first_name”: “John”, “last_name”: “Xiong”, “grade_level”: 8}, {“student_id”: “824”, “first_name”: “Ifa”, “last_name”: “Suibne”, “grade_level”: 4}, {“student_id”: “992”, “first_name”: “Gobannos”, “last_name”: “Tadhg”, “grade_level”: 6}, {“student_id”: “124”, “first_name”: “Mukhtaar”, “last_name”: “Onyekachi”, “grade_level”: 12}]}
The key here is to leverage the default parameter in the json.dumps() function because Students is a complex object. If you don’t, you’ll get an error like this:
TypeError: Object of type Student is not JSON serializable
If you were to only serialize a simple Student object, the default parameter wouldn’t be needed.
Hopefully that helps. Happy coding!