-1

I thought I could do the following to check if a data value was null and then substitute something else.

$.ajax({
    url: 'php/parsedjson.php',
    dataType: 'json',
    success: function(data) {
        $.each(data, function(index, val) {
            if (data[index].Manufacturers[0].Name != null){
             var manufacturer = data[index].Manufacturers[0].Name;}
             else{ var manufacturer ="MISSING"}
        });
    }
})

However, this throws an error Uncaught TypeError: Cannot read property 'Name' of undefined when the data value is not supplied in the JSON.

How do you check if there is a value to prevent this from happening?

jonmrich
  • 4,233
  • 5
  • 42
  • 94
  • 2
    check on data[index].Manufacturers.length first – Brent Boden Mar 08 '17 at 14:33
  • JSON is a *textual notation* for data exchange. [(More.)](http://stackoverflow.com/a/2904181/157247) If you're dealing with JavaScript source code, and not dealing with a *string*, you're not dealing with JSON. – T.J. Crowder Mar 08 '17 at 14:34
  • @T.J.Crowder Not sure what you mean, the data returned from my PHP is definitely in JSON format. – jonmrich Mar 08 '17 at 14:36
  • [i think is a duplicate](http://stackoverflow.com/questions/12770393/javascript-check-if-null-from-json). I hope i helped you – theodosis Mar 08 '17 at 14:38
  • @jonmrich: Yes, but that's not what you're dealing with. You're dealing with the result of *parsing* that JSON. It's not JSON anymore. It's just JavaScript objects. – T.J. Crowder Mar 08 '17 at 14:39

1 Answers1

1

Should be easy:

$.ajax({
    url: 'php/parsedjson.php',
    dataType: 'json',
    success: function(data) {
        $.each(data, function(index, val) {
            if (data[index].Manufacturers[0] && data[index].Manufacturers[0].Name){
             var manufacturer = data[index].Manufacturers[0].Name;}
             else{ var manufacturer ="MISSING"}
        });
    }
});

You have to check also data[index].Manufacturers[0] before getting to name, to avoid null pointers.

Roberto Lonardi
  • 569
  • 2
  • 10