0

I have a code to print the result in XML ,I need to print in json ,how can I do it using python

if format == 'XML':
        output += '<spellcheck-result>\n'
        for inputWord in corrections.keys():
            output += '<word>\n'
            result = {
                True  : 'CORRECT',
                False : 'INCORRECT'
            }[inputWord in corrections[inputWord].keys()]
            output += '<source status=\"' + result + '\">' + inputWord + "</source>\n"
            if result != 'CORRECT':
                for correction in corrections[inputWord].keys():
                    output += '<correction module=\"' + corrections[inputWord][correction] + '\">' + correction + "</correction>\n"
            output += '</word>\n'
        output += '</spellcheck-result>'
Mohamed Nizar
  • 780
  • 9
  • 30
  • There is no standard way to map between xml and json, so the json output would depend on how you specified it. You might have to parse the xml and convert it to json yourself. [This](http://stackoverflow.com/questions/191536/converting-xml-to-json-using-python) question may help. – Paul Rooney Jan 13 '16 at 05:35

1 Answers1

0

Check out xmltodict. It's fairly robust and creates a dictionary equivalent of an arbitrary XML tree. The reason why the XML to JSON mapping is somewhat hard to define boils down to ordering properties. xml2dict just converts the XML tree to an ordered dict + special key prefixes to describe XML attributes.

Once you have a python dict, just use the json module.

Thtu
  • 1,992
  • 15
  • 21