HOME | Blog | YouTube | LinkedIn | About Me         || Calculators    | SoftEng/Tech Posts    | Code/Scripts

Sunday, May 21, 2017

XML to Dictionary and JSON Conversion in Python

If you calling somebody else’s API and that API is returning XML, then you can convert that into a dictionary and/or JSON to use it in your Python code.
Here is what you need to do:
$ pip install xmltodict
Here is the code:
import xmltodict
import json

def main():
    print("main program")
    dict01 = convert_xml_to_dictionary("sample.xml")
    print("To: " + str(dict01["note"]["to"]))
    full_json_string = json.dumps(dict01, indent=4)
    print("Full json string: " + full_json_string)

def convert_xml_to_dictionary(xml_file, xml_attribs=True):
    with open(xml_file, "rb") as f:
        print("Doing the conversion...")
        my_dictionary = xmltodict.parse(f, xml_attribs=xml_attribs)
        return my_dictionary

if __name__ == "__main__": main()
Here is the XML file referenced in the code above:
    <body>Don't forget about the requirements</body>
Thank you for reading.
Almir Mustafic.

No comments:

Post a Comment