TypeError: Object of type is not JSON serializable
📁 Advanced Python Topics
I'm trying to write a Person class object to json like this:
def postUserToJson(user): fileName = str(user.FullName) + " - " + str(user.Id) file = open(pathUsers + fileName + ".json", "w", encoding="utf-8") json.dump(user, file, ensure_ascii=False) file.close()I'm getting an error:
TypeError: Object of type 'Person' is not JSON serializable I wouldn't say it's outright bad practice, you just need to approach it wisely, understand the implications, and not use it thoughtlessly.
The reasons to limit this practice, if you think about it, seem to me to be the following:
Explicit is better than implicit. You lose control over when exactly this code will be executed, and that can be important. Modules in Python can be imported not only at the top level, but also inside a function or method, which means the module code will be executed not during application startup, but when such a function is called and the
importstatement inside it is executed. Moreover, there may be more than one function importing the module, and which one executes first in your huge application can be far from obvious.
Log in to leave an answer