I have to save various properties of custom GTK elements to a file for future use and decided to use JSON because of the simple format and nesting of dicts.
Many properties are GTK enums, like gtk.PAGE_ORIENTATION_PORTRAIT
, gtk.ANCHOR_CENTER
and pango.ALIGN_LEFT
. They have a unique name which can be retrieved with obj.value_name
to get a valid JSON type.
Currently I have 2 methods for each of my elements: to_str()
to get the value_name and from_str()
which maps the str to the enum again. I would like to automate this so I don't forget to call these and clean up the code a bit. The JSONEncoder and JSONDecodr are doing exactly this, or so I thought...
This is the example given in the Python docs and it works as expected.
import json
class ComplexEncoder(json.JSONEncoder):
def default(self, obj):
print "default method called for:", obj
if isinstance(obj, complex):
return [obj.real, obj.imag]
return json.JSONEncoder.default(self, obj)
print json.dumps(2 + 1j, cls=ComplexEncoder)
Based on this example I've added the GTK enums:
import json
import gtk
ENUMS = [gtk.PAGE_ORIENTATION_PORTRAIT, gtk.PAGE_ORIENTATION_LANDSCAPE]
class GtkEncoder(json.JSONEncoder):
def default(self, obj):
print "default method called for:", obj
if obj in ENUMS:
return obj.value_name
return json.JSONEncoder.default(self, obj)
print json.dumps(gtk.PAGE_ORIENTATION_LANDSCAPE, cls=GtkEncoder)
Notice the added print statement in the default
method. In the original example, this method is called without problems, but not in the GTK example. The default
method is never called and it returns <enum GTK_PAGE_ORIENTATION_LANDSCAPE of type GtkPageOrientation>
which isn't valid JSON ofcourse.
So, is there a way to automatically encode/decode these enums or am I stuck with the current manual approach? Note that my data structure to dump is not a single value, but a dict or dicts.