简体   繁体   English

JScript JSON对象检查

[英]JScript JSON Object Check

I'm trying to check if json[0]['DATA']['name'][0]['DATA']['first_0'] exists or not when in some instances json[0]['DATA']['name'] contains nothing. 我正在尝试检查json [0] ['DATA'] ['name'] [0] ['DATA'] ['first_0']在某些情况下是否存在json [0] ['DATA'] ['name']不包含任何内容。

I can check json[0]['DATA']['name'] using 我可以使用以下命令检查json [0] ['DATA'] ['name']

if (json[0]['DATA']['name'] == '') {
    // DOES NOT EXIST
}

however 然而

if (json[0]['DATA']['name'][0]['DATA']['first_0'] == '' || json[0]['DATA']['name'][0]['DATA']['first_0'] == 'undefined') {
    // DOES NOT EXIST
}

returns json[0]['DATA']['name'][0]['DATA'] is null or not an object. 返回json [0] ['DATA'] ['name'] [0] ['DATA']为空或不是对象。 I understand this is because the array 'name' doesn't contain anything in this case, but in other cases first_0 does exist and json[0]['DATA']['name'] does return a value. 我了解这是因为数组'name'在这种情况下不包含任何内容,但是在其他情况下,first_0确实存在,并且json [0] ['DATA'] ['name']确实返回了一个值。

Is there a way that I can check json[0]['DATA']['name'][0]['DATA']['first_0'] directly without having to do the following? 有没有一种方法可以直接检查json [0] ['DATA'] ['name'] [0] ['DATA'] ['first_0'],而无需执行以下操作?

if (json[0]['DATA']['name'] == '') {
    if (json[0]['DATA']['name'][0]['DATA']['first_0'] != 'undefined') {
    // OBJECT EXISTS
    }
}

To check if a property is set you can just say 要检查是否设置了属性,您可以说

if (json[0]['DATA']['name']) {
  ...
}

unless that object explicitly can contain 0 (zero) or '' (an empty string) because they also evaluate to false . 除非该对象显式地可以包含0 (零)或'' (空字符串),因为它们的计算结果也为false In that case you need to explicitly check for undefined 在这种情况下,您需要显式检查undefined

if (typeof(json[0]['DATA']['name']) !== "undefined") {
  ...
}

If you have several such chains of object property references a utility function such as: 如果您有多个这样的对象属性链,请引用实用程序函数,例如:

function readProperty(json, properties) {
  // Breaks if properties isn't an array of at least 1 item
  if (properties.length == 1)
    return json[properties[0]];
  else {
    var property = properties.shift();
    if (typeof(json[property]) !== "undefined")
      return readProperty(json[property], properties);
    else
      return; // returns undefined
  }
}

var myValue = readProperty(json, [0, 'DATA', 'name', 0, 'DATA', 'first_0']);
if (typeof(myValue) !== 'undefined') {
  // Do something with myValue
}

so you're asking if you have to check if a child exists where the parent may not exist? 所以您问是否必须检查孩子是否存在,而父母可能不存在? no, I don't believe you can do that. 不,我不相信您可以做到。

edit: and just so it's not a total loss, what's with all the brackets? 编辑:只是这不是全部损失,所以所有括弧是什么?

json[0]['DATA']['name'][0]['DATA']['first_0']

could probably be 可能是

json[0].DATA.name[0].DATA.first_0

right? 对?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM