Created
March 27, 2010 00:00
-
-
Save aisipos/345559 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>") | |
>>> objectJSONEncoder().encode(obj) | |
'{"price": 1.5, "author": "W. Shakespeare"}' | |
""" | |
def default(self,o): | |
if isinstance(o, lxml.objectify.IntElement): | |
return int(o) | |
if isinstance(o, lxml.objectify.NumberElement) or isinstance(o, lxml.objectify.FloatElement): | |
return float(o) | |
if isinstance(o, lxml.objectify.ObjectifiedDataElement): | |
return str(o) | |
if hasattr(o, '__dict__'): | |
#For objects with a __dict__, return the encoding of the __dict__ | |
return o.__dict__ | |
return json.JSONEncoder.default(self, o) |
I tried unicode(o).encode('utf-8'), but it does not keep "\n" text in output json. Any idea?
Thanks. Slightly tweaked version here https://gist.github.com/gjask/f338a858c12f45635f6a85123646fd63
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for sharing this solution. I have tweaked it to handle Unicode by replacing the str() call in L17 with:
unicode(o).encode('utf-8')