检查嵌套 JSON 结构是否包含键

Check if nested JSON structure contains key

我正在尝试弄清楚如何检查一个深度嵌套的 JSON 对象(具有多个未知数组和属性)是否包含我正在寻找的 属性。我正在寻找一个名为 "isInvalid" 的 属性。如果该字段存在并且该键的值为真。我要return假。

var checkValidity = function (data) {
    for (var property in data) {
        if (data.hasOwnProperty(property)) {
            if (property == "isInvalid" && data[property] === true) {
                return false;
            }
            else {
                if (typeof data[property] === "object" && data[property] !== null) {
                    this.checkValidity(data[property]);
                }
            }
        }
    }
};

这是我一直在尝试的代码,但我无法让它工作。我也一直在研究下划线,但找不到所需的功能。有人有想法吗? (请不要注册)

你可以这样查看

var s = {a:'1',b:'2'};

if(Object.getOwnPropertyNames(s).indexOf('a') != -1){
console.log('available');
}else{
  console.log('Not available');
};

正在编辑答案... 更新

var s = {
  a1: '1',
  b: '2',
  c: {
    a: '11'
  }
};
var checkValidity = function (data) {
  if (Object.getOwnPropertyNames(data).indexOf('a') != - 1) {
    console.log('Found that key!!!');
  } else {
    for (var property in data) {

      if (Object.getOwnPropertyNames(property).indexOf('a') != - 1) {
         console.log('Found that key!!!');

      } else {
        if (typeof data[property] === 'object' && data[property] !== null) {
          console.log('not found continue in inner obj..');
          this.checkValidity(data[property]);
        }
      }
    }
  };
};
checkValidity(s);

它测试每个嵌套级别 属性 isInvalid,如果不是,则测试所有其他属性作为对象及其内容。 Array#every 如果一个 return 是 false.

则中断

function checkValidity(data) {
    return !data.isInvalid && Object.keys(data).every(function (property) {
        if (typeof data[property] === "object" && data[property] !== null) {
            return checkValidity(data[property]);
        }
        return true;
    });
}

var data = {
    a: 1,
    b: 2,
    c: {
        isInvalid: true,
        a: false
    }
};

document.write('checkValidity() should be false: ' + checkValidity(data) + '<br>');
data.c.isInvalid = false;
document.write('checkValidity() should be true: ' + checkValidity(data));

如果您真的只想检查 属性 的存在而不管它在 JSON 中的特定位置,那么 easiest/fastest 方法是在 源中搜索子字符串JSON 字符串。如果后者格式正确,则 属性 应在 JSON 中编码为 '"isInvalid":true'.

var checkValidity = function (jsonstr) {
    return jsonstr.indexOf('"isInvalid":true') >= 0;
}

对于像这样的复杂 json 搜索,我会使用 jsonpath ( http://goessner.net/articles/JsonPath/ ),它是 xpath 的 JSON 等价物。

要查找 isInvalid 字段,无论它在 json 中的什么位置,您可以像这样使用它:

 jsonPath(data, "$..isInvalid")