Convert gliderecord to a JSON object

G Balaji
Kilo Guru

Hi,

We've a transform map transforming data from source table to target table.

We're trying to set the value of a custom field in target table by concatenating all the import set table field values for a record by converting into a json key/value pair.

I tried to encode the source object and get an empty json value pair.

Is there any ways to implement this?

Thanks.

4 REPLIES 4

Ankur Bawiskar
Tera Patron
Tera Patron

Hi Balaji,

So I believe the target table's field is of type key:value then do following in the field map of that particular field

var obj = {}

obj.time1 = source.u_time1.toString();

obj.time2 = source.u_time2.toString();

return JSON.stringify(obj);

Mark Correct if this solves your issue and also mark 👍 Helpful if you find my response worthy based on the impact.
Thanks
Ankur

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

Simon Christens
Kilo Sage

You can use this script include:
Name: GrToJsonConverter

It takes a record (could be your source) and creates a JSON object with all of the information from the record.

var GrToJsonConverter = Class.create();
GrToJsonConverter.prototype = {
	initialize: function() {
	},
	
	convertGrToJSON : function(gr, returnValue){ // new GrToJsonConverter().convertGrToJSON(gr, 'str') // 'str' as 2nd paramter return as a string - else its an object
		
		var fields = new GlideRecordUtil().getFields(gr);
		fields.sort();
		
		var recordObj = {};
			
			for(var field in fields) {
				var type = gr.getElement(fields[field]).getED().getInternalType();
				
				if(type == 'boolean' || type == 'journal_input'){
					
					recordObj[fields[field]] = gr.getDisplayValue(fields[field]);		
				}else{
					
					recordObj[fields[field]] = gr.getValue(fields[field]);
				}
			}

			return returnValue == 'str' ? JSON.stringify(recordObj) : recordObj; 
		},
		
		type: 'GrToJsonConverter'
	};

Sanjay Bagri1
Tera Guru

Hi ,

You can go through the below link. it is a blog so you can get full idea .

Converting GlideRecord to JSON in ServiceNow

Please Mark as  Correct and 👍 Helpful.
Thanks
Sanjay Bagri

AbhishekGardade
Giga Sage

You may check out this blog:

JSON PARSING: USE CASE AND SOLUTIONS

Please mark as Correct Answer and Helpful, if applicable.
Thanks!
Abhishek Gardade
Hexaware Technologies

Thank you,
Abhishek Gardade