ServiceNow Learning#19: Convert XML Object to JSON in REST API.

Shamma Negi
Kilo Sage
Kilo Sage

Hi All,

 

It's a very common example that how we can convert our XML Response to JSON while calling REST API. Below is the live example of this scenario:

 

function doIt() {
  
    var request = new sn_ws.RESTMessageV2();
    request.setEndpoint('https://instance.service-now.com/api/now/table/incident/sys_id');
    request.setHttpMethod('GET');

    var user = 'user_name';
    var password = 'password';

    request.setBasicAuth(user, password);
    request.setRequestHeader("Accept", "application/xml");

    var response = request.execute();
    var res_body = response.getBody();// XML Response

    //gs.print('XML Response:\n\n' + response.getBody());

    var jsonObj = gs.xmlToJSON(res_body); // Converting XML into a JSON object

    gs.print('Number: ' + jsonObj.response.result.number);

    //var str = JSON.stringify(jsonObject); // Converting JSON object into a String
}

doIt();

 Please use this wherever you want to convert the xml object to JSON.

 

How to convert an XML payload into JSON in ServiceNow - Support and Troubleshooting

 

Regards,

Shamma

Regards,Shamma Negi
2 REPLIES 2

Christopher Nan
Tera Expert

This isn't a bad way to do it at all, but be careful using the xmlToJson api.  I haven't checked in the last two releases, but this api didn't use Java streaming when I worked on it at ServiceNow.  When it was originally published it didn't have any limits on size and could hang an instance if the xml string was to large.  The fix to this was decided to just put a limit on it and it returns nothing if the xml string passed in is over a certain size.  So using this on larger xml strings will cause it to not work.  

 

Ultimately unless you know the exact size that will always be returned from the xml rest api, I'd suggest never using xmlToJson in a production environment.  

For any xml strings larger than a simple xml object it's suggested to use the XMLDocument2 api which doesn't have size limits because it uses Java streaming IO under the hood.  

yeah true that. I will write a best practice on XMLDocument2 as well.

 

Thanks for suggesting this.

 

Regards,

Shamma

Regards,Shamma Negi