ServiceNow Learning#19: Convert XML Object to JSON in REST API.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
08-10-2023 02:54 AM
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
- 2,412 Views
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
08-10-2023 06:20 AM - edited 08-10-2023 06:21 AM
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.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
08-11-2023 04:55 AM
yeah true that. I will write a best practice on XMLDocument2 as well.
Thanks for suggesting this.
Regards,
Shamma