Skip to content

Instantly share code, notes, and snippets.

@gjask
Forked from aisipos/objectifiedJson.py
Last active January 13, 2017 17:06
Show Gist options
  • Save gjask/f338a858c12f45635f6a85123646fd63 to your computer and use it in GitHub Desktop.
Save gjask/f338a858c12f45635f6a85123646fd63 to your computer and use it in GitHub Desktop.
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