Class Serialization using vars()

Useful technique for serializing classes to JSON using vars()

Created: August 9th 2019
Updated: December 7th 2019
Connect with us on

This demo showcases a useful technique for serializing classes to JSON using the vars() method.


Some terms to help you navigate the post


A method that takes a class instance and returns a dict of the instance attributes


JSON is a file format used to store data in key-value pairs. More information can be found here


You can run the demo code and actually run it by running python or python3

Real World Applications

This method is useful if you are writing a simple application that needs to serve class instances via a REST endpoint, or are looking for easy serialization to a cross platform format.


This file is here to create a sample class to show off the vars() method
class user:
    def __init__(self, name, age, birthday, country, address):
        A generic user class to store information about people.
        name : string
        User instances' name
        age : int
        User instances' age
        birthday : string
        User instances' birthday
        Country : string
        User instances' current country location
        address : string
        User instances' address
        """ = name
        self.age = age
        self.birthday = birthday = country
        self.address = address

"""A demo of the vars function, specifically it's usage to expedite JSON serialization
vars() is a function that takes an object instance as an argument and returns a dict
of the instance attributes.
SEE: vars documentation
import json # Used to serialize data to a JSON file SEE:
from example_class import user # Dummy class to instantiate, and serialize

example_user = user("John Doe", 21, "22-10-1995", "Australia", "123 Main Street") # Instantiate an example to use later
print("User class vars output: ")

# outputs: {'name': 'John Doe', 'age': 21, 'birthday': '22-10-1995', 'country': 'Australia', 'address': '123 Main Street'}

# You can use vars with json.dump to serialize a class instance to a json file
json.dump(vars(example_user), open("user.json", "w"))

Thank you for your support!

Be sure to share the post if it was helpful!