IBM Support

How to convert XML to JSON in a format other than BadgerFish using DataPower Gateway?

Question & Answer


Question

How to convert XML to JSON in a format other than BadgerFish using DataPower Gateway?

Answer

If you need the XML converted in other JSON formats, you can add following gateway script after the "xml-to-json" policy:
var util = require('util'); 
 var bfJson = apim.getvariable('message.body'); 
 //console.alert(JSON.stringify(bfJson)); 
 var plainJson = {}; 
 convertBadgerfishToPlainJSON(bfJson, plainJson ); 
 //console.alert(JSON.stringify(plainJson)); 
 apim.setvariable('message.body', plainJson); 
 apim.output('application/json'); 
  
 function convertBadgerfishToPlainJSON(inputDocument,outputDocument) { 
   for (var property in inputDocument) { 
     // namespace and attribute properties start with an @, so ignore them 
     if (property.slice(0, 1) != '@') { 
       // get this property's value. 
       var propertyObj = inputDocument[property]; 
       // for namespaces, badgerfish includes the namespace property name, so strip it out 
       var i = property.indexOf(':'); 
       if (i >= 0) { 
         property = property.slice(i + 1); 
       } 
  
       // process the property's object based on its type 
       var type = util.safeTypeOf(propertyObj); 
       switch (type) { 
       case 'object': 
         // objects, a child of $ is the property's value 
         if(propertyObj['$']) { 
           outputDocument[property] = propertyObj['$']; 
         } else { 
           // an object without a child $, this property has child objects, so recurse to convert the children 
           outputDocument[property] = {}; 
           convertBadgerfishToPlainJSON(propertyObj,outputDocument[property]) 
         } 
         break; 
       case 'array': 
         // any array, recurse to convert the array children 
         outputDocument[property] = []; 
         convertBadgerfishToPlainJSON(propertyObj,outputDocument[property]) 
         break; 
       default: 
         // don't think we should get here, but just in case, set the property to its scalar value 
         outputDocument[property] = propertyObj; 
         break; 
       } 
     } 
   } 
 }

[{"Business Unit":{"code":"BU053","label":"Cloud & Data Platform"},"Product":{"code":"SS9H2Y","label":"IBM DataPower Gateway"},"Component":"","Platform":[{"code":"PF009","label":"Firmware"}],"Version":"All Versions","Edition":"","Line of Business":{"code":"LOB45","label":"Automation"}}]

Document Information

Modified date:
30 March 2020

UID

ibm16120717