Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a Custom Class JSON serializable

Tags:

python

json

class

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

like image 789
code base 5000 Avatar asked Apr 15 '14 15:04

code base 5000


People also ask

Can JSON be serialized?

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.

How do you serialize a JSON in Python?

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.

Is Python set JSON serializable?

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.

How do you make an object serializable in Python?

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.


1 Answers

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"}'
like image 170
FrobberOfBits Avatar answered Oct 25 '22 23:10

FrobberOfBits