I have a custom class, let's call is class ObjectA(), and it have a bunch of functions, property, etc.., and I want to serialize object using the standard json library in python, what do I have to implement that this object will serialize to JSON without write a custom encoder?
Thank you
Json namespace provides functionality for serializing to and deserializing from JavaScript Object Notation (JSON). Serialization is the process of converting the state of an object, that is, the values of its properties, into a form that can be stored or transmitted.
Working With JSON Data in Python The json module exposes two methods for serializing Python objects into JSON format. dump() will write Python data to a file-like object. We use this when we want to serialize our Python data to an external JSON file. dumps() will write Python data to a string in JSON format.
You are here because when you try to dump or encode Python set into JSON, you received an error, TypeError: Object of type set is not JSON serializable . The built-in json module of Python can only handle Python primitives types that have a direct JSON equivalent.
Module Interface. To serialize an object hierarchy, you simply call the dumps() function. Similarly, to de-serialize a data stream, you call the loads() function. However, if you want more control over serialization and de-serialization, you can create a Pickler or an Unpickler object, respectively.
Subclass json.JSONEncoder, and then construct a suitable dictionary or array.
See "Extending JSONEncoder" behind this link
Like this:
>>> class A: pass
...
>>> a = A()
>>> a.foo = "bar"
>>> import json
>>>
>>> class MyEncoder(json.JSONEncoder):
... def default(self, obj):
... if isinstance(obj, A):
... return { "foo" : obj.foo }
... return json.JSONEncoder.default(self, obj)
...
>>> json.dumps(a, cls=MyEncoder)
'{"foo": "bar"}'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With