How to convert XML to JSON in Node.JS

The process of converting between XML and JSON formats is generally a rather dry and tedious undertaking. To counter this drudgery, I’m going to show you how to apply an API to the situation, allowing us to save a huge amount of time and effort.

Installation of the client that we need can be carried out by dropping this reference into our package.json file.

"dependencies": {
"cloudmersive-convert-api-client": "^2.1.6"
}

Next step, call convertDataXmlToJson.

var CloudmersiveConvertApiClient = require('cloudmersive-convert-api-client');var defaultClient = CloudmersiveConvertApiClient.ApiClient.instance;// Configure API key authorization: Apikeyvar Apikey = defaultClient.authentications['Apikey'];Apikey.apiKey = 'YOUR API KEY';// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)//Apikey.apiKeyPrefix = 'Token';var apiInstance = new CloudmersiveConvertApiClient.ConvertDataApi();var inputFile = "/path/to/file"; // File | Input file to perform the operation on.var callback = function(error, data, response) {if (error) {console.error(error);} else {console.log('API called successfully. Returned data: ' + data);}};apiInstance.convertDataXmlToJson(inputFile, callback);

With our function set up, we just have to provide an XML file and let our API go to work on it, returning us the JSON. Simple.

Image for post
Image for post

Written by

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store