检查嵌套的JSON结构是否包含密钥

时间:2016-02-17 08:04:23

标签: javascript json underscore.js

我正在试图弄清楚如何检查一个深度嵌套的JSON对象,其中有几个未知数组和属性包含我正在寻找的属性。我正在寻找一个名为“isInvalid”的属性。如果该字段在那里并且该键的值为true。我想要归还假。

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]);
                }
            }
        }
    }
};

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

4 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

你可以这样检查

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);

答案 2 :(得分:1)

它测试属性isInvalid的每个嵌套级别,如果不是,则测试所有其他属性作为对象及其内容。如果一次返回falseArray#every会中断。



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));
&#13;
&#13;
&#13;

答案 3 :(得分:0)

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

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

 jsonPath(data, "$..isInvalid")