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.

split multi line string and create json

went james
Kilo Explorer

i want to split the string from \n\n and converted it into json object in Business Rule script

"VM to be provisioned for which region? = APAC\n\nLease Type = Temporary\n\nStart = 2021-04-07 14:53:17\n\nEnd = 2021-06-06 14:53:19\n\nSize = Basic A0 | 1 Core | 768 MB\n\nUsed for = Development\n\nBusiness purpose = test\n\n"

1 ACCEPTED SOLUTION

Ankur Bawiskar
Tera Patron
Tera Patron

@went james 

try this

Script:

var str = "VM to be provisioned for which region? = APAC\n\nLease Type = Temporary\n\nStart = 2021-04-07 14:53:17\n\nEnd = 2021-06-06 14:53:19\n\nSize = Basic A0 | 1 Core | 768 MB\n\nUsed for = Development\n\nBusiness purpose = test\n\n";

var arr = str.split('\n\n');

var obj = {};

for(var i=0;i<arr.length;i++){

var str1 = arr[i];

if(str1){
var arr1 = str1.split('=');

var key = arr1[0].trim();
var value = arr1[1].trim();

obj[key] = value;

}
}

gs.info(JSON.stringify(obj));

Output:

[0:00:00.065] Script completed in scope global: script


Script execution history and recovery available here


*** Script: {"VM to be provisioned for which region?":"APAC","Lease Type":"Temporary","Start":"2021-04-07 14:53:17","End":"2021-06-06 14:53:19","Size":"Basic A0 | 1 Core | 768 MB","Used for":"Development","Business purpose":"test"}

Regards
Ankur

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

View solution in original post

6 REPLIES 6

@ankur

everything is fine just I want output :

{"VM to be provisioned for which region?":"APAC"},{"Lease Type":"Temporary"},{"Start":"2021-04-07 16:01:12"}

 

what need to make changes.

Then ensure the loop runs only till 3 and not complete length

for(var i=0;i<3;i++){

Regards
Ankur

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