cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
1224
Views
0
Helpful
1
Replies

CVP REST Client Parsing JSON array response

From below response body I'm trying to capture "type" from phoneNumbers array and this is the syntax I'm using $.phoneNumbers[1].type. It works fine as long as that array exists. However my REST response varies every time based on input and array size also changes from 1 to 4.

 

So question in place is how do I get array count so I don't have to parse JSON objects that doesn't exist. 

 

As of now since max array count is 4, I'm parsing all 4 arrays of "type" and "number" in action element and getting error.

 

Response Body:

{
"firstName": "John",
"lastName" : "doe",
"age" : 26,
"address" : {
"streetAddress": "naist street",
"city" : "Nara",
"postalCode" : "630-0192"
},
"phoneNumbers": [
{
"type" : "iPhone",
"number": "0123-4567-8888"
},
{
"type" : "home",
"number": "0123-4567-8910"
}
]
}

 

Error from Activity logs:

05/20/2020 15:44:04.373,jsParseJSON,custom,type,sun.org.mozilla.javascript.internal.WrappedException: Wrapped com.jayway.jsonpath.PathNotFoundException: Array index [Ljava.lang.String;@379bb10a not found in path (<Unknown source>#4) in <Unknown source> at line number 4
05/20/2020 15:44:04.373,jsParseJSON,exit,

05/20/2020 15:44:04.373,,element,error,

 

Syntax in Set Value element:

importPackage(com.audium.server.cvpUtil);
var inputJSON= {Data.Element.Rest_Client_01.response_body};
var path="$.type[2].cptCodeDescription";
JSONPathUtil.eval(inputJSON,path);

1 Reply 1

Mark Pareja
Level 1
Level 1

You would need to loop through each array element and look for the element with the property your interested in

var inputJSON= Data.Element.Rest_Client_01.response_body;
var phoneNumbers=inputJSON.phoneNumbers;

When dealing with raw JSON I don't see the value of calling the cvpUtil library. You can deconstruct the response object the same way you would w/ any other JSON object.Then we store the Array to a variable for code cleanliness.

var cptCodeDescription;

Declare a variable we will return regardless of the outcome

for( var i = 0; i < phoneNumbers.length; i++ ){ if(phoneNumbers[ i ].type == "home" ){
cptCodeDescription = phoneNumbers[ i ].cptCodeDescription
}

Iterate over the array insuring the child object has the value you're interested in.
Store your value to the variable we defined above.

if (!cptCodeDescription){
cptCodeDescription = "none"
}


Here we check if the value is present in the variable, this would hopefully avoid throwing a null pointer exception when leaving rhino. It allows you to log this value (to help troubleshoot) and inspect this value in a decision element.

eval(cptCodeDescription)


Return your data to setLocalVar
This example assumes you are familiar enough with the requested data schema and are confident that type "home" would only appear once in the array.