How to convert XML to JSON in Node.JS
1 min readApr 10, 2020
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.