-2

I am getting below json data:

{
  "ID": [
    "The i d field is required."
  ],
  "terms_condition": [
    "The terms condition field is required."
  ]
}

and stored in variable:

var DataJson = data.responseText;
var Json = JSON.parse(DataJson);

var IdError = Json.ID[0];
var TermsConditionError = Json.terms_condition[0];

Now I am getting this error Uncaught TypeError: Cannot read property '0' of undefined when ID is not exists

I have tried with this example to prevent error handling.

if (typeof Json.ID[0] !== 'undefined') {
    alert('validation message found');
} else {
    alert('validation message not found');
}

but this is not working any idea what i am doing wrong?

Thanks.

Mr.Happy
  • 2,559
  • 8
  • 32
  • 67

2 Answers2

2

Try this.

 if (Json !=undefined && typeof Json.ID[0] != undefined ) {
        alert('validation message found');
    } else {
        alert('validation message not found');
    }

TypeError: Cannot read property '0' of undefined

This error occurs when main json object is either empty or undefined. This happens when there is no data in json object.

Dhiraj
  • 1,302
  • 9
  • 17
1

To check whether a variable or a field is defined you can compare it with undefined

if ((Json !== undefined) && (Json.ID !== undefined) && (Json.ID[0] !== undefined)) {
    alert('validation message found');
} else {
    alert('validation message not found');
}

I don't see any issue in your code. See the snippet below.

var Json = JSON.parse('{"ID": ["The i d field is required."], "terms_condition": ["The terms condition field is required."]}');

var IdError = Json.ID[0];
var TermsConditionError = Json.terms_condition[0];

document.writeln(IdError + '<br>');
document.writeln(TermsConditionError + '<br>');
document.writeln('==================<br>');

function isDefined(Json) {
  return (Json !== undefined) && (Json.ID !== undefined) && (Json.ID[0] !== undefined);
}
  
var inputData = [
  undefined,
  {},
  {ID: ''},
  {ID: ['value']}
];

inputData.forEach(function(inputDaten) {
  document.writeln(JSON.stringify(inputDaten) + ': ' + isDefined(inputDaten) + '<br>');
});

Probably the issue is with data.responseText

Alexander Elgin
  • 5,926
  • 4
  • 33
  • 47