JavaScript Convert XML to JSON: A Beginner Guide – JavaScript Tutorial

By | April 12, 2020

XML and JSON are two formats to share data among different applications. In this tutorial, we will introduce how to convert xml to json in javascript. You can implement it by following our tutorial.

Preliminary

We will use open source xmlToJson to do it.

javascript convert xml to json

How to use xmlToJson to convert xml to json?

You should import some js files.

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="xmlToJson.js"></script>
<script src="main.js"></script>

Then you can convert a xml string to json string.

function transform() {
  var input = document.getElementById('xmltext').value;
  var json = xmlToJson.parse(input);
  document.getElementById('jsontext').innerHTML = '<pre>' + JSON.stringify(json, null, 4) + '</pre>';
}

We can use xmlToJson.parse(input) funtion to convert a xml string (input) to json, then get the json string by JSON.stringify(json, null, 4).

Leave a Reply

Your email address will not be published. Required fields are marked *