Code Premix

How to convert XML to JSON in JavaScript

📅September 8, 2021

Today we’ll show you how to convert XML to JSON in JavaScript. In this article, we will show you how to convert XML strings to JSON using the xml2json script.

  1. Create HTML page
  2. Import JS library
  3. Add script
  4. Output

1. Create HTML page

Let’s create a simple HTML page to convert the XML to JSON. Use the below code to create a HTML page.

index.html


<html>

<head>
  <style>
    body {
      font-family: monospace;
    }

    #xmlToJSON {
      margin-top: 20px;
      line-height: 25px;
    }
  </style>
</head>

<body>
  <h2>Convert XML to JSON - <a href="https://codepremix.com/" target="_blank" rel="noopener noreferrer">Code Premix</a></h2>
  <div>
    <h4>XML:</h4>
    <textarea id="xmlString" cols="55" rows="15"></textarea>
  </div>
  <button id="xmlToJSON">Convert XML to JSON</button>
</body>

</html>

2. Import JS library

In the next step, we have to add the following jQuery library in the head section of the page.

<script type='text/javascript' src='https://code.jquery.com/jquery-3.5.1.min.js'></script>
<script type='text/javascript' src="https://cdn.rawgit.com/abdmob/x2js/master/xml2json.js"></script>

Here, we have imported the xml2json library for conversion.

3. Add script

Now add the following script to read the XML string from textarea and convert it into the JSON.

index.html

<script>
  $(document).ready(function () {
    $("#xmlToJSON").click(function () {
      var data = $("#xmlString").val();
      var xmlData = "";
      if (data !== null && data.trim().length !== 0) {
        try {
          xmlData = $.parseXML(data);
        } catch (e) {
          throw e;
        }
        var x2js = new X2JS();
        data = x2js.xml2json(xmlData);
        console.log(data);
      }
    });
  });
</script>

4. Output

Let’s combine all code together and check the output in the browser.

index.html


<html>

<head>
  <script type='text/javascript' src='https://code.jquery.com/jquery-3.5.1.min.js'></script>
  <script type='text/javascript' src="https://cdn.rawgit.com/abdmob/x2js/master/xml2json.js"></script>
  <style>
    body {
      font-family: monospace;
    }

    #xmlToJSON {
      margin-top: 20px;
      line-height: 25px;
    }
  </style>
  <script>
    $(document).ready(function () {
      $("#xmlToJSON").click(function () {
        var data = $("#xmlString").val();
        var xmlData = "";
        if (data !== null && data.trim().length !== 0) {
          try {
            xmlData = $.parseXML(data);
          } catch (e) {
            throw e;
          }
          var x2js = new X2JS();
          data = x2js.xml2json(xmlData);
          console.log(data);
        }
      });
    });
  </script>
</head>

<body>
  <h2>Convert XML to JSON - <a href="https://codepremix.com/" target="_blank" rel="noopener noreferrer">Code Premix</a></h2>
  <div>
    <h4>XML:</h4>
    <textarea id="xmlString" cols="55" rows="15"></textarea>
  </div>
  <button id="xmlToJSON" onclick="">Convert XML to JSON</button>
</body>

</html>

You can use the below sample XML code to convert it into the JSON format.

<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications with XML.</description>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.</description>
   </book>
   <book id="bk103">
      <author>Corets, Eva</author>
      <title>Maeve Ascendant</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-11-17</publish_date>
      <description>After the collapse of a nanotechnology society in England, the young survivors lay the foundation for a new society.</description>
   </book>
   <book id="bk104">
      <author>Corets, Eva</author>
      <title>Oberon's Legacy</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2001-03-10</publish_date>
      <description>In post-apocalypse England, the mysterious agent known only as Oberon helps to create a new life for the inhabitants of London. Sequel to Maeve
      Ascendant.</description>
   </book>
   <book id="bk105">
      <author>Corets, Eva</author>
      <title>The Sundered Grail</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2001-09-10</publish_date>
      <description>The two daughters of Maeve, half-sisters, battle one another for control of England. Sequel to Oberon's Legacy.</description>
   </book>
</catalog>