filter jQuery.getJSON results

Asked

Viewed 135 times

1

I’m making a jQuery.getJSON at the url http://api.vagalume.com.br/search.php

And should JSON return:

{"type":"notfound"}

or

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

I didn’t want to run some codes, I tried how:

 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’s wrong with:

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

He’s going into the if and making a mistake:

Uncaught Typeerror: Cannot read Property '0' of Undefined

in the data.mus[0].text

  • 2

    Use && in place of ||

  • Thanks Leandro.... Would you know tell me how in js I do a check to know if date.Mus[0]. Translate[0]. text exists? sometimes this tag doesn’t come in json and then error.

1 answer

1


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

To avoid the error just check first if the field exists before trying to read the data:

if (data.mus != null && data.mus.length > 0 && data.mus[0] != null)
// agora é seguro usar data.mus[0] neste ponto
  • perfect, that’s right, but do I need to do this 3 checks? only if (date.Mus[0] != null) would not be enough?

  • I don’t think you can simplify it, no, it has to be all three checks anyway. The problem is that so, for you to get the first element of the list, it cannot be null first (data.Mus != null) , and after that the list cannot be empty (data.mus.length > 0) Otherwise it will give error of attempt of access in index outside the limits of the vertor. Now the third check is for the case that the vector exists && is not empty but the element is null (data.Mus[0] != null) would still give the error of trying to access a null object Property.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.