Options
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
03-12-2022 05:08 AM
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