-
-
Save gjask/f338a858c12f45635f6a85123646fd63 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import simplejson as json | |
import lxml | |
class objectJSONEncoder(json.JSONEncoder): | |
"""A specialized JSON encoder that can handle simple lxml objectify types | |
>>> from lxml import objectify | |
>>> obj = objectify.fromstring("<Book><price>1.50</price><author>W. Shakespeare</author></Book>") | |
>>> json.dumps(obj, cls=objectJSONEncoder) | |
'{"price": 1.5, "author": "W. Shakespeare"}' | |
""" | |
model = ( | |
(lxml.objectify.IntElement, int), | |
(lxml.objectify.NumberElement, float), | |
(lxml.objectify.FloatElement, float), | |
(lxml.objectify.ObjectifiedDataElement, | |
lambda s: unicode(s).strip().encode('utf-8')), | |
) | |
def default(self,o): | |
for o_type, constructor in self.model: | |
if isinstance(o, o_type): | |
return constructor(o) | |
if hasattr(o, '__dict__'): | |
#For objects with a __dict__, return the encoding of the __dict__ | |
return [item.__dict__ for item in o] | |
return json.JSONEncoder.default(self, o) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment