Possible Duplicate:
Converting XML to JSON using Python?
I’m doing some work on App Engine and I need to convert an XML document being retrieved from a remote server into an equivalent JSON object.
I’m using xml.dom.minidom to parse the XML data being returned by urlfetch. I’m also trying to use django.utils.simplejson to convert the parsed XML document into JSON. I’m completely at a loss as to how to hook the two together. Below is the code I’m tinkering with:
from xml.dom import minidom
from django.utils import simplejson as json
#pseudo code that returns actual xml data as a string from remote server.
result = urlfetch.fetch(url,'','get');
dom = minidom.parseString(result.content)
json = simplejson.load(dom)
self.response.out.write(json)
Soviut’s advice for lxml objectify is good. With a specially subclassed simplejson, you can turn an lxml objectify result into json.
See the docstring for example of usage, essentially you pass the result of lxml
objectifyto the encode method of an instance ofobjectJSONEncoderNote that Koen’s point is very valid here, the solution above only works for simply nested xml and doesn’t include the name of root elements. This could be fixed.
I’ve included this class in a gist here: http://gist.github.com/345559