Way to check If Multiple Keys exist in a JSON Payload

vtred
Tera Contributor

Hi, I would like to know if there is a straight forward way to check if multiple Keys present in a JSON payload

I need to check if the Key exist and if the key do not exist -- I must set a dummy value and save.
I tried to use: "response.hasOwnProperty('Key1')" --> in this case, i just check if Key1 is present... where as i need to check if every key exist without writing multiple if/else blocks for each key.

 

Example: This is just an example payload, whereas actual payload has more than 20 keys. 

[ {

      "Key1":"Value1",

     "Key2":"Value2",

     "Key3":"Value3",

     "Key4":"Value4",

 

}]

2 REPLIES 2

DScroggins
Kilo Sage

Hello,

 

You can easily check for the existence of a particular key value like so:

var obj = {

     "Key1":"Value1",

     "Key2":"Value2",

     "Key3":"Value3",

     "Key4":"Value4", 

}

var tstKey = 'Key3';


if(!!obj[tstKey])
  gs.print('its there');
else
  gs.print('not there');

 

If your returned object is inside an array as in your above example you can then add an index either directly or using a while loop like so:

var obj = [ {

      "Key1":"Value1",

     "Key2":"Value2",

     "Key3":"Value3",

     "Key4":"Value4",

 

}];


var tstKey = 'Key3';

//Uning direct index

if(!!obj[0][tstKey])
  gs.print('there');
else
  gs.print('not there');

//Using loop

for(i in obj){

if(!!obj[i][tstKey])
  gs.print('there');
else
  gs.print('not there');

}

 

Hope this helps.

 

--David

Hitoshi Ozawa
Giga Sage
Giga Sage

There are several ways to check.

Method 1:

function hasKeys(jsonObj, keyList) {
  for (var i=0; i< keyList.length; i++) {
    //if (!jsonObj[0][keyList[i]]) {
    if (!(keyList[i] in jsonObj[0])) {
      return false;
    }
  }
  return true;
}

var keyList = ["Key1", "Key3"];  // array of keys to check if they exists

var str = '[{"Key1":"Value1", "Key2":"Value2","Key3":"Value3","Key4":"Value4"}]';  // json
var jsonObj = JSON.parse(str);

gs.info(hasKeys(jsonObj, keyList));  // check if keys in keyList exists in jsonObj

Methods 2:

function hasKeys2(keys, keyList) {
  return keyList.every(function(val) { return keys.indexOf(val) >= 0; });
}

var keyList = ["Key1", "Key3"];

var str = '[{"Key1":"Value1", "Key2":"Value2","Key3":"Value3","Key4":"Value4"}]';
var jsonObj = JSON.parse(str);
var keys = Object.keys(jsonObj[0]);  // extract all keys from jsonObj

gs.info(hasKeys2(keys, keyList));

Execution:

Case 1: All keys exist

var keyList = ["Key1", "Key2", "Key3"];

var str = '[{"Key1":"Value1", "Key2":"Value2","Key3":"Value3","Key4":"Value4"}]';

Result:

*** Script: true

Case 2: A key does not exist

var keyList = ["Key1", "Key2", "Key3"];

var str = '[{"Key1":"Value1", "Key3":"Value3","Key4":"Value4"}]'; // removed "Key2"

Result:

*** Script: false