DEV Community

Kevin Mack
Kevin Mack

Posted on • Originally published at welldocumentednerd.com on

Quickly Deserializing in Python

Just a quick “Tip and Trick” post right now, but I’ve been doing a lot of work with python lately. And I have to tell you, I’m really enjoying it. Python provides a lot of easy ways to do the kind of work that we have to do so often. The “Free form” nature of python gives the ability to build a lot of things very quickly, and one of the common problems I wanted to solve is pulling in configuration information into your python scripts.

One of the habits I’ve built over my time as a developer is that I HATE to build magic strings, and prefer to build configuration settings as I build my code. And rely upon this configuration almost immediately. And as I’ve been working with python, I found an easy way to handle this type of pattern.

The first benefit, is how Python handles json, when Python reads in a json script, it will treat it as a type “dict” which is great because it makes it really easy to read as a key / value pair. So for example, the following code works:

Below is the test.json:


{
    "value1":"value 2",
    "object1": {
        "objectvalue1":"test"
    }
}

Enter fullscreen mode Exit fullscreen mode

The following python script can read that:


filePath = "./test.json"
f = open(filePath)
config = json.load(f)
f.close()

value1 = config["value1"]

Enter fullscreen mode Exit fullscreen mode

Honestly pretty easy, but one of the fun tricks of python I recently discovered is how to map those values to a class. Take the following file for “test.json”


{
    "value1":"value 2",
    "object1": {
        "objectvalue1":"test1"
        "objectvalue2":"test2"
    }
}

Enter fullscreen mode Exit fullscreen mode

And if I create the following class:


class Object1(object):
    def __init__ (self, objectvalue1, objectvalue2):
        self.objectvalue1 = objectvalue1
        self.objectvalue2 = objectvalue2

Enter fullscreen mode Exit fullscreen mode

I can load that class with the following:


filePath = "./test.json"
f = open(filePath)
config = json.load(f)
f.close()

object1 = Object1(**config["object1"])

Enter fullscreen mode Exit fullscreen mode

That one line at the end will take the json object from the “object1” property and will match it to the constructor to load the object, and do it based on name mapping, so as long as the constructor parameters match the names of the json file it will take care of the mapping.

So just a fun little trick for python for anyone who’s new to python.

Top comments (0)