Back to Blog

June 1, 2022

Saving a Class to JSON File

Saving a class to a JSON file is not a trivial task, because classes are not your typical object to save into a JSON file.

Let's jump right into the code and write the method for exporting the results to a JSON file as a dictionary.

def write_resutls_to_json(filename, rows):
    with open(filename, 'w') as outfile:
        json.dump(rows, outfile)

Now if your run the code and arrive at the export method call, you will get an error like this one:

TypeError: Object of type 'Product' is not a JSON serializable.

The message tells you everything: an instance of the Product class is not serializable. To overcome this little obstacle, let's use a trick:

def write_results_to_json(filename, rows):
    with open(filename, 'w') as outfile:
        json.dump(list(map(lambda p: p.__dict__, rows)), outfile)

And that's all! 🎉