...

Saving A Class Into Json File

Frank Casanova

June 1, 2022

...

Saving a class to aJSON file is not a trivial task, because classes are not

your typical object to save into a JSON file.

 

    Lets 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

and error like this one.

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

    the message tells you everything: an instace 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)

_______________________________________________________________________

 

Aaaaaand thats all.