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.

How to get the JSON key and value. How to get the length of parent.

Raj82
Kilo Expert

I have converted the XML into JSON. But I am unable to get any values from that Json. Also I am not able to get the length. Please help. I want to know how many info there and I want to get the key and value from each info node. I consider each info is single record.

 

{
"soap:Envelope": {
"xmlns:soap": "http://www.w3.org/2003/05/soap-envelope",
"soap:Body": {
"customerListResponse": {
"xmlns": "http://ei2.nobj.nable.com/",
"return": [

{
"info": [
{
"value": "622",
"key": "customer.customerid"
},
{
"value": "All Covered - Workspaces",
"key": "customer.customername"
}
]
},

 

{
"info": [
{
"value": "623",
"key": "customer.customerid"
},
{
"value": "1All Covered - Workspaces 1",
"key": "customer.customername"
}
]
}
]
}

 


}
}
}

1 ACCEPTED SOLUTION

To get the length of Info:

 var req = JSON_FILE; 

 var totalRecords = req["soap:Envelope"]["soap:Body"]["customerListResponse"]["return"].length;

 

 

To get the key and value in first "Info":

 

 var key = req["soap:Envelope"]["soap:Body"]["customerListResponse"]["return"][0].info[0].key;

var value = req["soap:Envelope"]["soap:Body"]["customerListResponse"]["return"][0].info[0].value;

 

Thanks,

Raj

View solution in original post

12 REPLIES 12

Dubz
Mega Sage

Something like this:

var json = JSON.parse(<your JSON file>);
var returnObj = json.return;
gs.log(returnObj.length);

for (var i=0; i< returnObj.length; i++){
gs.log(returnObj[i].key + ' - ' + returnObj[i].value);
}

Did you tried this in your PDI? Because I have used the fix script, I am not able to save this script in my fix script.

 

 It shows error in the below line.

--> var returnObj = json.return;

 

Error: Could not save record because of a compile error: JavaScript parse error at line (27) column (28) problem = missing name after . operator (<refname>; line 27)

 

 

The below is my json file, can you please try this in your PDI?

 

Sample Json:

{
"soap:Envelope": {
"xmlns:soap": "http://www.w3.org/2003/05/soap-envelope",
"soap:Body": {
"customerListResponse": {
"xmlns": "http://ei2.nobj.nable.com/",
"return": [

{
"info": [
{
"value": "622",
"key": "customer.customerid"
},
{
"value": "All Covered - Workspaces",
"key": "customer.customername"
}
]
},

 

{
"info": [
{
"value": "623",
"key": "customer.customerid"
},
{
"value": "1All Covered - Workspaces 1",
"key": "customer.customername"
}
]
}
]
}

 


}
}
}

Yeah fair enough, the actual path would be:

json.soap:Body.customerListResponse.return

But it's going to hiccup over the soap:Body name, the colon is oging to be unexpected

Yes, That is my problem.