xmltodict turn module xml format into the format json

1.1: xmltodict turn module xml format into the format json

<? Xml Version = "1.0" ?>                     <-! # Version -> 
< the Data >                                     <-! #Data is a label just write, data contained three sets of data, each set of data are country tag - -> 
    < country name = "Liechtenstein" >     <-! #NAME country is to take the name tag -> 
        < Rank Updated = "yes" > 2 </ Rank >     <-! # two </ rank> 2 is a data ranking, updated = "yes" attribute can be easily written -> 
        < year > 2008 </ year >                 <-! # 2008 ->
        <gdppc>141100</gdppc>            <!--#人均gdp是141100-->
        <neighbor name="Austria" direction="E"/>          <!--#他有个邻居有两个属性 name 和 direction-->
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank updated="yes">69</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>
xmltest.xml original data
# ! / Usr / bin / Python the env 
# - * - Coding: UTF-. 8 - * - 
Import xmltodict, JSON 

with Open ( ' xmltest.xml ' , ' R & lt ' ) AS F: 
    str_xml = STR (reached, f.read () ) 

str_xml = str_xml.replace ( ' & ' , ' & # 38 is; ' )   # XML format is not the "&" symbol 
DOC = xmltodict.parse (str_xml)
 Print json.dumps (DOC)
xml_to_json.py
{
    "data": {
        "country": [{
            "@name": "Liechtenstein",
            "rank": {
                "@updated": "yes",
                "#text": "2"
            },
            "year": "2008",
            "gdppc": "141100",
            "neighbor": [{
                "@name": "Austria",
                "@direction": "E"
            }, {
                "@name": "Switzerland",
                "@direction": "W"
            }]
        }, {
            "@name": "Singapore",
            "rank": {
                "@updated": "yes",
                "#text": "5"
            },
            "year": "2011",
            "gdppc": "59900",
            "neighbor": {
                "@name": "Malaysia",
                "@direction": "N"
            }
        }, {
            "@name": "Panama",
            "rank": {
                "@updated": "yes",
                "#text": "69"
            },
            "year": "2011",
            "gdppc": "13600",
            "neighbor": [{
                "@name": "Costa Rica",
                "@direction": "W"
            }, {
                "@name": "Colombia",
                "@direction": "E"
            }]
        }]
    }
}
json file parsed

 

Guess you like

Origin www.cnblogs.com/jiaxinzhu/p/12596105.html