简体   繁体   English

如何使用python将其打印为Json

[英]How to print this as Json using python

I have a code to print the result in XML ,I need to print in json ,how can I do it using python 我有一个代码以XML打印结果,我需要以json打印,如何使用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>'

Check out xmltodict . 查看xmltodict It's fairly robust and creates a dictionary equivalent of an arbitrary XML tree. 它相当健壮,可以创建相当于任意XML树的字典。 The reason why the XML to JSON mapping is somewhat hard to define boils down to ordering properties. 从XML到JSON的映射很难定义的原因归结为排序属性。 xml2dict just converts the XML tree to an ordered dict + special key prefixes to describe XML attributes. xml2dict只是将XML树转换为有序dict +特殊键前缀来描述XML属性。

Once you have a python dict, just use the json module. 有了python字典后,只需使用json模块即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM