How to check for missing Json element

knight
Tera Expert

I have below Json body from Google contact api

[

{"number":0,

"fields":[

{

"min":99999,

"max":999999999,

"label":"",

"type":"number",

"value":133136}

]},

{"number":1,

"fields":[

{

"min":99999,

"max":999999999,

"label":"",

"type":"number",

"value":1231244}

]

}

]

I have almost 5000 thousand records some of them having missing value":1231244 I have written below to check for missing element but its not working, I am using it to test in Scripts-Background. It doesn't print from If condition but goes in catch block and print     *** Script: Inside catch undefined. Any suggestion how to check for undefined element and skip going to catch block.

try {

var r = new sn_ws.RESTMessageV2('Google Contact API Test', 'Default GET');

r.setAuthentication('oauth2', 'Google default_profile');

var response = r.execute();

var responseBody = response.getBody();

var parser = new JSONParser();

var parsedData = parser.parse(responseBody);

var length = parsedData.length;

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

if(parsedData[i].fields[0].value==undefined){

gs.print('not defined');

}

}

catch(ex) {

var message = ex.getMessage();

gs.print('Inside catch ' + message);

}

1 ACCEPTED SOLUTION

Giles Lewis2
Kilo Expert

Your logic for detecting a missing value works, but you are not blowing up where you think you are blowing up. Git rid of the outer try/catch block, then replace the code inside your loop with the following


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


  try {


      if(parsedData[i].fields[0].value==undefined){


          gs.print('not defined');


      }


  }


  catch(ex) {


      gs.print(ex + '\n' + JSON.stringify(parsedData[i]));


  }


}


View solution in original post

1 REPLY 1

Giles Lewis2
Kilo Expert

Your logic for detecting a missing value works, but you are not blowing up where you think you are blowing up. Git rid of the outer try/catch block, then replace the code inside your loop with the following


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


  try {


      if(parsedData[i].fields[0].value==undefined){


          gs.print('not defined');


      }


  }


  catch(ex) {


      gs.print(ex + '\n' + JSON.stringify(parsedData[i]));


  }


}