filter results jQuery.getJSON

1

I'm doing a jQuery.getJSON on url link

And if JSON returns:

{"type":"notfound"}

or

{"type":"song_notfound","art":{"id":"3ade68b7ga05f0ea3","name":"William Bald\u00e9","url":"http:\/\/www.vagalume.com.br\/william-balde\/"}}

I did not want to run some code, I tried like:

 if (data.type != "notfound" || data.type != "song_notfound") {
                    // Letra da música
                    $("#letraescrita").html("");

                    $("#letraescrita").html('<h3>Paroles: </h3><a href=' + data.mus[0].url + ' target=_blank>clique aqui</a><Br>' + data.mus[0].text);

                    $("#traducao").html("");
                    $("#traducao").html('<h3>traduction: </h3><Br>' + data.mus[0].translate[0].text);
                }

But I think something is wrong with:

 if (data.type != "notfound" || data.type != "song_notfound") {

It is entering inside if and giving error:

  

Uncaught TypeError: Can not read property '0' of undefined

no data.mus[0].text

    
asked by anonymous 29.07.2015 / 22:20

1 answer

1

The error is because some of the JSON records do not have the field you are trying to access.

To avoid the error simply check first if the field exists before attempting to read the data:

if (data.mus != null && data.mus.length > 0 && data.mus[0] != null)
// agora é seguro usar data.mus[0] neste ponto
    
30.07.2015 / 23:46