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.

Set dynamic key value in json

Eash1
Tera Expert

I am trying to set dynamic value to my Key in Json object but its setting the variable name instead.

var primaryObj = source.u_bp_primary_object_type.toString(); //dynamic values
var secondayObj = source.u_bp_secondary_object_type.toString(); //dynamic values

var payload = {
"app_key": appKey.toString(),
"status": source.u_bp_incident_status.toString(),
primaryObj : source.u_bp_primary_objects.toString(),  // Issue in line
secondayObj : source.u_bp_secondary_objects.toString(), //Issue in line
"servicenow_ticket_created": "false"
};

 

When i print the obj - 

{

"app_key": "123123",

"status":"warning",

"primaryObj":"RTUS00375SV001",

"secondayObj":"High Memory - Warning",

"servicenow_ticket_created":"false"

}

 

how to add dynamic key to json object.

 

Thank you,

Easwar

1 ACCEPTED SOLUTION

Manish Vinayak1
Tera Guru

Try setting those properties after creating the object. 

Try the following code:

var primaryObj = source.u_bp_primary_object_type.toString(); //dynamic values
var secondayObj = source.u_bp_secondary_object_type.toString(); //dynamic values

var payload = {
"app_key": appKey.toString(),
"status": source.u_bp_incident_status.toString(),
"servicenow_ticket_created": "false"
};

payload[primaryObj] = source.u_bp_primary_objects.toString();
payload[secondayObj] = source.u_bp_secondary_objects.toString();

Here's the example I tried:

var dynamicKey = "value3"; 
var payload = { 
"value1": "text1", 
"value2" : "text2", 
}; 
payload[dynamicKey] = "text3"; 


gs.print(JSON.stringify(payload));

 Results:

*** Script: {"value1":"text1","value2":"text2","value3":"text3"}

Hope this helps!

Cheers,

Manish

 

 

 

 

View solution in original post

1 REPLY 1

Manish Vinayak1
Tera Guru

Try setting those properties after creating the object. 

Try the following code:

var primaryObj = source.u_bp_primary_object_type.toString(); //dynamic values
var secondayObj = source.u_bp_secondary_object_type.toString(); //dynamic values

var payload = {
"app_key": appKey.toString(),
"status": source.u_bp_incident_status.toString(),
"servicenow_ticket_created": "false"
};

payload[primaryObj] = source.u_bp_primary_objects.toString();
payload[secondayObj] = source.u_bp_secondary_objects.toString();

Here's the example I tried:

var dynamicKey = "value3"; 
var payload = { 
"value1": "text1", 
"value2" : "text2", 
}; 
payload[dynamicKey] = "text3"; 


gs.print(JSON.stringify(payload));

 Results:

*** Script: {"value1":"text1","value2":"text2","value3":"text3"}

Hope this helps!

Cheers,

Manish