Pet projects: flask app to convert xml to json

Pet projects: flask app to convert xml to json

First let us understand what xml is

Full form of XML is eXtensible Markup language. As the name suggests XML is a markup language like HTML but the difference is that XML focuses on what the data is whereas HTML focuses on what the data looks, like if you open up xml file, it will just show all of the data of the file with the tags, whereas if you open up a HTML file, it will add the "beautification" through the tags used, which takes us to the next difference which is that the tags used in xml do not mean anything, they are defined by the user, whereas in HTML tags are predefined.

XML stores data as simple text, so it very easy to store and share without the fear of data loss or the file being incompatible between computers.

As xml does not contain info on how to display it, the data and presentation are independent of each other, so the same XML file can be presented in different ways. We can also use xml to store the data and HTML to format and display the said data.

XML is used in many industries to describe day-to-day data transactions:

  • Stocks and Shares

  • Financial transactions

  • News information

  • Weather services

XML document

<?xml version="1.0" encoding="UTF-8"?>
<nitf>
  <head>
    <title>King surpasses God</title>
  </head>
  <body>
    <headline>
      <hl1>Kohli scores record breaking 50 ODI centuries</hl1>
    </headline>
    <byline>
      <bytag>By Sammith Bharadwaj, Associated Press Writer</bytag>
    </byline>
    <dateline>
      <location>Mumbai, Maharahstra</location>
      <date>November 15 17:41 IST</date>
    </dateline>
  </body>
</nitf>

XML tree structure

An XML Document (X_Movie) & its tree representation (T_Movie)

XML documents act like trees which start from a root and keeps branching out with child elements.

XML documents rules

  • XML needs to have a root

  • Every element must have a closing tag

  • Attribute values must be quoted

  • tags must be properly nested

  • Case sensitive

Attributes act as identity for different siblings within a parent.

In the above screenshot you can see id is an attribute. Attributes must be unique, elements need not be.

Now onto the creating a flask to do this part. We can use xmltodict package to convert the xml to json. This is a pretty simple flask app to do the same, let us start with app.py

from flask import Flask, render_template, request, jsonify
import xmltodict

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/convert', methods=['POST'])
def convert_xml_to_json():
    try:
        xml_data = request.form['xml_data']
        json_data = xmltodict.parse(xml_data)
        return jsonify(json_data)
    except Exception as e:
        return jsonify({'error': str(e)}),400

if __name__ == '__main__':
    app.run(debug=True)

Here we have written the conver_xml_to_json() function that parses the xml data that we have written and returns a json.

Html file:

<!DOCTYPE html>
<html>
<head>
    <title>XML to JSON Converter</title>
    <link rel="icon" type="image/x-icon" href="/static/favicon.jpg">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        .container {
            display: flex;
        }
        .editor {
            flex: 1;
            margin: 5px;
        }
        .jsonOutput {
            width: 100%;
            height: 300px;
            border: 1px solid #ccc;
            overflow: auto;
        }
        .error {
            color: red;
        }
    </style>
</head>
<body>
    <h1>XML to JSON Converter</h1>
    <div class="container">
        <div class="editor">
            <h3>XML Editor</h3>
            <textarea id="xmlInput" style="width:100%; height:300px;"></textarea>
            <br>
            <button onclick="convertXmlToJson()">Convert</button>
        </div>
        <div class="editor">
            <h3>JSON Output</h3>
            <pre id="jsonOutput" class="jsonOutput"></pre>
            <p id="errorMessage" class="error"></p>
        </div>
    </div>

    <script>
        function convertXmlToJson() {
            var xmlData = $('#xmlInput').val();
            $.ajax({
                type: 'POST',
                url: '/convert',
                data: {'xml_data': xmlData},
                success: function(response) {
                    $('#jsonOutput').text(JSON.stringify(response, null, 4));
                    $('#errorMessage').text('');
                },
                error: function(xhr, status, error) {
                    $('#errorMessage').text('Error: ' + xhr.responseText);
                    $('#jsonOutput').text('');
                }
            });
        }
    </script>
</body>
</html>

In the HTML side of things there is not much explanation to do other than the fact that we are using just HTML and jquery. An AJAX(Asynchronour JavaScript and XML) request is made when we click on convert and gives us the response when request is successful or else print out the error.

I have deployed the code on render as well as hosted the code on Github, you can check out the website as well as the code.