Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

How to convert XML to JSON?

Ranjit Singh R1
Kilo Expert

I have made a SOAP call and I am getting a response. I have a parameter in the Response which is base64 encoded. So I have parsed that parameter and decoded it. Now the decoded value looks familier however I have to convert the decoded string into JSON so that I can easily dot walk to the objects and fetch those values. Here is the script for that: 

    var responseBodyRetrieveReport = responseRetrieveReport.getBody();
    var statusRetrieveReport = responseRetrieveReport.getStatusCode();
    gs.info('statusRetrieveReport:' + statusRetrieveReport);
    gs.info('statusRetrieveReport:' + responseBodyRetrieveReport);
    var xmlDocTokenRetrieveReport = new XMLDocument2();
    xmlDocTokenRetrieveReport.parseXML(responseBodyRetrieveReport);
    var tokenRetrieveReport = xmlDocTokenRetrieveReport.getNode("//ReportStream").getTextContent();
    gs.info('statusRR:' + tokenRetrieveReport);
    var decodedString = gs.base64Decode(tokenRetrieveReport);
	gs.info('statusRRR:' + decodedString);

I am getting a log in the variable decodedString and I have to convert that XML body to JSON. Please suggest.

Note: I am using scoped Application

Thank you.

10 REPLIES 10

Hi,

So you are getting response and it includes some base64Encoded data.

you are decoding it

what next?

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

Yes, the decoded value is in XML and I would like to convert it to JSON so that I can then easily dotwalk and fetch the element values.

Hi,

so is the decoded value a valid xml string.

Did you try to check that?

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

Yes, I have checked it, it is a valid XML. 

I am able to convert the same XML using online XML to JSON converter, however I ma not able to do so using script. Any help with the script would be helpful.

Here is the script which I am using to covert to JSON:

 gs.info('statusRR:' + tokenRetrieveReport);
    var decodedString = gs.base64Decode(tokenRetrieveReport);
	gs.info('statusRRR:' + decodedString);
	var okHelper = new  global.OkXMLHelper();
var okObj = okHelper.toObject(decodedString);
	//var okStr = JSON.stringify(okObj, null, 2);
	var okStr = JSON.stringify(okObj);
	gs.info('statusRRRR:'+okStr);