Make Python class JSON serializable---Object of type SampleClass is not JSON serializable

I encountered a problem of converting a special class to json during work and study, and then I found this article, which is pretty good.

You are here because when you try coding custom Python objects to JSON format, you receive a type error : Object of type SampleClass is not JSON serializable. In this article, I will show you how to serialize any Python object to JSON so that you can convert any custom Python object to data in JSON format.

Python's built-in json module can only handle Python basic types that have direct JSON equivalents. That is, the fundamental problem is that the JSON encoders json.dump() and json.dumps()  only know how to serialize the set of basic object types (for example, dictionaries, lists, strings, numbers, None, etc.) by default.

To solve this problem, we need to build a custom encoder to make our Class JSON serializable.

There are multiple ways to make Python-like JSON serializable. You can choose the one that best suits the complexity of your problem. Let us understand one by one.

Goals of this course :

  • Write your own custom JSON encoder to make the JSON class serializable
  • Create custom toJSON()method to make Python class JSON serializable
  • Use the jsonpickle  module to serialize JSON
  • How to inherit a class dictto make the class JSON serializable

Because I have not obtained the translation authorization (have not responded to me yet), and did not find any reprinting or translation instructions, so I can give you some suggestions. Please check the original link for the specific content. The English is easy to understand, and you can also use the plug-in to translate the whole web page.

Author:

About Vishal

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Original English link: https://pynative.com/make-python-class-json-serializable/

Thanks for the selfless sharing of the original author !

Guess you like

Origin blog.csdn.net/qq_41914687/article/details/114105870