This demo showcases a useful technique for serializing classes to JSON using the vars() method.
language-essentials
Description
This demo showcases a useful technique for serializing classes to JSON using the vars() method.
Definitions
vars()
A method that takes a class instance and returns a dict of the instance attributes.
JSON
JSON is a file format used to store data in key-value pairs. More information can be found here
Usage
Running
In this repo you can see the demo code and actually run it by running python vars.py
or python3 vars.py
.
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.
Files
example_class_demo.py
"""
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.
Parameters
----------
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
"""
self.name = name
self.age = age
self.birthday = birthday
self.country = country
self.address = address
vars_demo.py
"""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 https://docs.python.org/3/library/functions.html#vars
"""
import json # Used to serialize data to a JSON file SEE: https://docs.python.org/3/library/json.html
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'}
print(vars(example_user))
# 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"))