List with Jquery, second JSON index

Asked

Viewed 99 times

0

Good evening friends, I have the following json which is originated from a url, the result is exactly this:

{
"cod": "OS78946",
"serv": "Pré pago",
"passo": "7894",
"ocorridos": [

    {
        "data": "21\/02\/2020",
        "hora": "19:38",
        "onde": "Pato Branco\/PR",
        "oque": [
            "teste um"
        ]
    },

    {
        "data": "21\/02\/2020",
        "hora": "18:09",
        "onde": "Maringa\/PR",
        "oque": [
            "teste dois"
        ]
    },

    {
        "data": "21\/02\/2020",
        "hora": "17:00",
        "onde": "Muriaé\/MG",
        "oque": [
            "teste oito"
        ]
    }
]}

Follow my code, following this line of reasoning, how to list the values of "date", "time" and "what" that are inside the object "occurred"? I locked in the last line of javascript.

<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE-edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>

</head>
<body>
  <div class="d-flex justify-content-center" id="teste">
    <div class="">Resultado
      <h5 id="h5-teste"></h5>
      <p id="cod"></p>
      <p id="serv"></p>
      <p id="passo"></p>
      <p id="lista_ocorridos"></p>
    </div>
  </div>

<script type="text/javascript">
$(function(){
$.ajax({
url: 'https://localhost/1.json',
dataType: 'json',
success: function(volta){
if(volta.status == "ERROR"){
alert(volta.message + "Inacessível no momento, tente mais tarde");
return false;
}
$("#cod").html(volta.cod);
$("#serv").html(volta.serv);
$("#passo").html(volta.passo);
//$("#lista_ocorridos")...;
}});
});
</script>

</body>
</html>

  • occurred is an array, you need to do a for/foreach to list all its values

3 answers

0

Since the event is an array, you can access its contents as follows:

    $.each(volta.ocorridos, function(index, obj) {
  console.log(obj.data);
  console.log(obj.hora);
  console.log(obj.onde);
  $.each(obj.oque, function(index2, obj2) {
    console.log(obj2);
  });
});

0


As I commented, ocorridos is an array, so you need to access each element of the array in order to list its contents. The same thing for oque which is also an array. You can do this for example using the command for:

var volta = {
"cod": "OS78946",
"serv": "Pré pago",
"passo": "7894",
"ocorridos": [
    {
        "data": "21\/02\/2020",
        "hora": "19:38",
        "onde": "Pato Branco\/PR",
        "oque": [
            "teste um"
        ]
    },

    {
        "data": "21\/02\/2020",
        "hora": "18:09",
        "onde": "Maringa\/PR",
        "oque": [
            "teste dois"
        ]
    },
    {
        "data": "21\/02\/2020",
        "hora": "17:00",
        "onde": "Muriaé\/MG",
        "oque": [
            "teste oito"
        ]
    }
]};


for(var i=0; i< volta.ocorridos.length; i++) {
   var item = volta.ocorridos[i];
   console.log(item.data + " " + item.hora);
   for (var j=0; j<item.oque.length; j++) {
      console.log(item.oque[j]);
   }
}

  • Ricardo, in the case of my code, You need to adapt something to include your? To include, I’m a beginner in javascript. Thanks in advance for your attention

  • part of for you can use directly in your code right after you close the if(volta.status == "ERROR"){. Anyway, try to understand what has been done and ask if you need, if just copying and using the code will not help you ;)

0

Just complementing as they said... a full implementation in jQuery would be:

<html lang="pt-BR">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE-edge" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />

    <script
      src="https://code.jquery.com/jquery-3.4.1.min.js"
      integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
      crossorigin="anonymous"
    ></script>
  </head>
  <body>
    <div class="d-flex justify-content-center" id="teste">
      <div class="">
        Resultado
        <h5 id="h5-teste"></h5>
        <p id="cod"></p>
        <p id="serv"></p>
        <p id="passo"></p>
        <br />
        <label>forma 1</label>
        <ul id="lista_ocorridos"></ul>
        <br />
        <label>forma 2</label>
        <ul id="lista_ocorridos2"></ul>
      </div>
    </div>

    <script type="text/javascript">
      $(function() {
        $.ajax({
          url:
            "https://localhost/1.json",
          dataType: "json",
          success: function(volta) {
            if (volta.status == "ERROR") {
              alert(volta.message + "Inacessível no momento, tente mais tarde");
              return false;
            }
            console.log(volta);
            $("#cod").html(volta.cod);
            $("#serv").html(volta.serv);
            $("#passo").html(volta.passo);

            if (Array.isArray(volta.ocorridos)) {
              // forma 1
              const ocorridos = volta.ocorridos;
              for (let index = 0; index < ocorridos.length; index++) {
                const ocorrido = ocorridos[index];
                $("#lista_ocorridos").append(
                  `<li id='ocorrido${index}'><p> Cidade: ${ocorrido.onde}</li>`
                );

                if (Array.isArray(ocorrido.oque)) {
                  const oques = ocorrido.oque;
                  for (let index2 = 1; index2 <= oques.length; index2++) {
                    const oque = oques[index2 - 1];
                    $(`#ocorrido${index}`).append(
                      `<ul id='oques'><li>${index2}: ${oque}  </li></ul>`
                    );
                  }
                }
              }

              // forma 2
              $("#lista_ocorridos2").html(
                `${volta.ocorridos.reduce((acumulador, ocorrido) => {
                  return (acumulador += `<li>
                    <p>Cidade: ${ocorrido.onde}<p>
                    ${Array.isArray(ocorrido.oque) &&
                      `<p>Motivos:
                        <ul>
                          ${ocorrido.oque.reduce(
                            (acc, oq, index) =>
                              (acc += `<li> ${++index}: ${oq}</li>`),
                            ""
                          )}
                        </ul>
                      <p>`}
                  </li>`);
                }, "")}`
              );
            }
          }
        });
      });
    </script>
  </body>
</html>

There are other ways to do it besides the two examples! Use indentation in your code for better eligibility (some languages only work like this, e.g.: python, lua), an editor like VS Code with plugins can make it much easier for you to indent/format your code ;).

Browser other questions tagged

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