While this post is specific to changing serialized JSON data from python classes, the main idea is to leverage a dictionary to replace your object names.
Leveraging most of the code from a previous post where the json object names have their associated class attribute names with underscores, this is one way to take your serialized JSON object names and replace the underscores with spaces:
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
def replace_json(incoming_json):
string_json = str(incoming_json)
json_replace_dict = {'student_id':'student id',
'first_name':'first name',
'last_name':'last name',
'grade_level':'grade level'}
for k, v in json_replace_dict.items():
string_json = string_json.replace(k, v)
return string_json
# 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)
updated_json = replace_json(json.dumps(students.__dict__, default=lambda o: o.__dict__))
print(updated_json)
From the output below, we can see the student class attributes that have underscores now have spaces. So “student_id” is now “student id”:
{“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}]}
Happy coding!