Python class to json string
Problem
Sometimes you need to convert a python class into a json string.
Solution
There are a lot of different ways of doing it, but one that I normally use is by defining the following method in the class:
import json
class ...:
...
def to_json(self):
return json.dumps(self, default=lambda o: dict((key, value) for key, value in o.__dict__.items() if value), sort_keys=True, allow_nan=False, indent=False)
As you can see there are a few options for configuring the json.dumps method, some of the most interesting:
- sort_keys: to order the json fields alphabetically.
- allow_nan: to include nulls / None fields.
- indent: to pretty print the json.
Example
A full example:
import json
class Person:
def __init__(self, name, surname, age):
self.name = name
self.surname = surname
self.age = age
def __str__(self):
return f"Person(name='{self.name}', surname='{self.surname}', age={self.age})"
def to_json(self):
return json.dumps(self, default=lambda o: dict((key, value) for key, value in o.__dict__.items() if value), sort_keys=True, allow_nan=False)
if __name__ == '__main__':
p1 = Person("Name", "Surname", 10)
print(p1)
print(p1.to_json())
Which prints the following on the console:
# print(p1)
Person(name='Name', surname='Surname', age=10)
# print(p1.to_json())
{"age": 10, "name": "Name", "surname": "Surname"}
Example with nested structures
This approach also works with nested structures:
import json
class Job:
def __init__(self, name):
self.jobName = name
class Person:
def __init__(self, name, surname, age, jobs):
self.name = name
self.surname = surname
self.age = age
self.jobs = jobs
def to_json(self):
return json.dumps(self, default=lambda o: dict((key, value) for key, value in o.__dict__.items() if value), sort_keys=True, allow_nan=False)
if __name__ == '__main__':
p1 = Person("Name", "Surname", 10, [Job("Teacher")])
print(p1.to_json())
{"age": 10, "jobs": [{"jobName": "Teacher"}], "name": "Name", "surname": "Surname"}