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.

parse json array to get key value pair

Reshma77
Tera Contributor

Hello All,

I am trying to populate key-value pair from multi row variable set of incident table. With below code I am getting JSON array

var gr = new GlideRecord('incident');
gr.addQuery('number=INC0001164');
gr.query();
if (gr.next()) {
var mrvs = gr.variables.employee_details;
gs.print(mrvs);
}

*** Script: [ {
  "name" : "7db62c631b655150ded9eca8ab4bcb90",
  "number" : "007810",
  "manager" : "ABC",
  "cost" : "01394040"
} ]

If I try to parse the multi row variable set (var Payload = JSON.parse(mrvs); gs.print(Payload);) I am getting below result

Script: [object Object]

Can somebody help to get only key value pair from the JSON array. I am using this code in template script that needs to be populated on the ticket
The format should look like below

 

Name: ABC

Number: INC0001164
Manager: XYZ

Thanks,

1 ACCEPTED SOLUTION

Prasad Dhumal
Mega Sage

Hello Reshma,

Using the following code, you can iterate through the JSON array and print the key-value pairs:

var gr = new GlideRecord('incident');
gr.addQuery('number', 'INC0001164');
gr.query();
if (gr.next()) {
var mrvs = gr.variables.employee_details;
var Payload = JSON.parse(mrvs);
for (var i = 0; i < Payload.length; i++) {
var obj = Payload[i];
var keys = Object.keys(obj);
for (var j = 0; j < keys.length; j++) {
var key = keys[j];
if (key == "name") {
gs.print("Name: " + obj[key]);
}
if (key == "manager") {
gs.print("Manager: " + obj[key]);
}
}
}
}

View solution in original post

5 REPLIES 5

Chetan Mahajan
Kilo Sage

Hi @Reshma77 ,

                          you can use below code for key-value pair. modify query according to your requirement

var obj = {};
var gr = new GlideRecord('incident');
gr.query();
if (gr.next()) {
    var vars = gr.variables.getValue();
    for (var i = 0; i < vars.size(); i++) {
        var row = vars.get(i);
        obj[row.name] = row.value;
    }
}
gs.print(JSON.stringify(obj));

Kindly mark correct and helpful if applicable