views:

222

answers:

3

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.

I can check json[0]['DATA']['name'] using

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. 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.

Is there a way that I can check json[0]['DATA']['name'][0]['DATA']['first_0'] directly without having to do the following?

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

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?

lincolnk
Yep, that's what I'm asking. Thanks.
George
+1  A: 

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. In that case you need to explicitly check for 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
}
RoToRa
A: 

I have used all the above ways. But still I'm getting the same exception

is null or not an object

I'm trying to check whether

JSONobject.word.annotation.comment.id73[0]

is present or not. Actually that object is not set.

My original JSON value is here http://stackoverflow.com/questions/3385820/json-find-the-length-of-objects

Please help me in this.

Vinothkumar Arputharaj