Python Snippet: Converting a complex object to json

Here’s a simple recipe, to convert most Python class-objects to json and back.

Here’s the setup:

import json

class Foo:
    def __init__(self, name, values):
        self.name = name
        self.values = values

Converting to json:

an_object = Foo('John', (123, 456, 789))

json_string = json.dumps(vars(an_object))

Quite simple, isn’t it? Using the vars function, Python converts the object to a dictionary which can then be jsonified, using the json.dums function.

The reverse is quite simple as well:

a_fresh_object = Foo(**json.loads(json_string))

This simply takes the output of json.loads, which is a dict, and maps the keys and values of that dict to the names arguments of Foo’s __init__ method.

Nifty.

So long…

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s