Access JSON with multiple JS objects

Asked

Viewed 3,189 times

3

I have the following JSON

[
  {
    "id": 1,
    "nome": "Matheus Almeida Siccenna",
    "cpf": null,
    "matricula": {
      "id": 555,
      "empresa": 1,
      "unidade": 0,
      "descricaoUnidade": null,
      "curso": 1,
      "descricaoCurso": null,
      "serie": 1,
      "descricaoSerie": null,
      "turma": 3,
      "descricaoTurma": null,
      "periodo": "Manhã",
      "ativo": false
    },
    "contato": {
      "email": "[email protected]",
      "ddd": "41",
      "telCelular": "(41)123456789",
      "telResidencial": "123456789",
      "telComercial": "12345-6789"
    }
}
]

and I wanted to access the data with the JS I usually make a for(i in response.content) and I’m accessing with the response.content[i].nome, but I’m not getting it. It’s returning undefined. Someone knows what it is?

(JSON is received via $.get)

  • Post your Javascript code

  • Post as you receive this JSON, so I understand there is no error: http://jsfiddle.net/filadown/5mpw4zL1/

  • What gives alert(typeof response.content);?

4 answers

1

You’re getting your file .json in server text format. The best way to resolve this is to change your server code to upload the file .json with the header appropriate. In PHP it would look something like this:

<?php
$data = ''; // Seu JSON vai aqui
header('Content-Type: application/json');
echo json_encode($data);

That way, when you get the file via $.get() jQuery itself will make the appropriate conversion and return you a Javascript object.


Now, if you don’t have access to the server code that sends the file .json, just do the conversion inside the function $.get() using the function JSON.parse(), that takes a string and returns an object. Example:

$.get(
  'https://gist.githubusercontent.com/tayllan/ea6a43e6ee843a4a3c05/raw/c7713343dc5e68843bd8646b80a5d80898fc4c79/104024.json',
   function(response) {
     response = JSON.parse(response);

     for (var i = 0; i < response.length; i++) {
        document.write(response[i].nome + '<br>'); // "Matheus Almeida Siccenna"
        document.write(response[i].contato.email); // "[email protected]"
     }
   }
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

0

Play this result in a variable and work with it.

var dataJson = [
  {
    "id": 1,
    "nome": "Matheus Almeida Siccenna",
    "cpf": null,
    "matricula": {
      "id": 555,
      "empresa": 1,
      "unidade": 0,
      "descricaoUnidade": null,
      "curso": 1,
      "descricaoCurso": null,
      "serie": 1,
      "descricaoSerie": null,
      "turma": 3,
      "descricaoTurma": null,
      "periodo": "Manhã",
      "ativo": false
    },
    "contato": {
      "email": "[email protected]",
      "ddd": "41",
      "telCelular": "(41)123456789",
      "telResidencial": "123456789",
      "telComercial": "12345-6789"
    }
}
];
$('div').html(dataJson[0].nome);
  • 1

    Pq of the negative?

0

See if it clears up

var json = [{
  "id": 1,
  "nome": "Matheus Almeida Siccenna",
  "cpf": null,
  "matricula": {
    "id": 555,
    "empresa": 1,
    "unidade": 0,
    "descricaoUnidade": null,
    "curso": 1,
    "descricaoCurso": null,
    "serie": 1,
    "descricaoSerie": null,
    "turma": 3,
    "descricaoTurma": null,
    "periodo": "Manhã",
    "ativo": false
  },
  "contato": {
    "email": "[email protected]",
    "ddd": "41",
    "telCelular": "(41)123456789",
    "telResidencial": "123456789",
    "telComercial": "12345-6789"
  }
}];

dump(json);

function dump(obj) {
  $.each(obj, function(chave, valor) {
    console.log(chave, valor, $.type(valor));

    if ($.type(valor) == 'object') {
      dump(valor)
    } else {
      $('div').append(chave + ':' + valor + '<br>')
    }
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>

0

Works perfectly here, just declare the variable i:

Javascript:

var response = [
                {
                  "id": 1,
                  "nome": "Matheus Almeida Siccenna",
                  "cpf": null,
                  "matricula": {
                    "id": 555,
                    "empresa": 1,
                    "unidade": 0,
                    "descricaoUnidade": null,
                    "curso": 1,
                    "descricaoCurso": null,
                    "serie": 1,
                    "descricaoSerie": null,
                    "turma": 3,
                    "descricaoTurma": null,
                    "periodo": "Manhã",
                    "ativo": false
                  },
                  "contato": {
                    "email": "[email protected]",
                    "ddd": "41",
                    "telCelular": "(41)123456789",
                    "telResidencial": "123456789",
                    "telComercial": "12345-6789"
                  }
              }
            ];
var content='';
for (var i in response) {
   content+='<h3>Dados do estudante:</h3>\
          <div class="usuario">Id: '+response[i].id+'<br>\
                  Nome: '+response[i].nome+'<br>\
                  CPF: '+response[i].cpf+'<br>\
          </div>\
          <h3>Matrícula:</h3>\
          <div class="matricula">Id matrc: '+response[i].matricula.id+'<br>\
                  Empresa: '+response[i].matricula.empresa+'<br>\
                  Unidade: '+response[i].matricula.unidade+'<br>\
                  Curso: '+response[i].matricula.curso+'<br>\
                  Série: '+response[i].matricula.serie+'<br>\
                  Período: '+response[i].matricula.periodo+'<br>\
         </div>\
         <h3>Informações de contato:</h3>\
         <div class="contato">Email: '+response[i].contato.email+'<br>\
                  DDD: '+response[i].contato.ddd+'<br>\
                  Tel Celular: '+response[i].contato.telCelular+'<br>\
                  Tel Residencial: '+response[i].contato.telResidencial+'<br>\
                  Tel Comercial: '+response[i].contato.telComercial+'<br>\
         </div>';
}
document.getElementById('content').innerHTML=content;

HTML:

<div id="content"></div>

Example jsfiddle

Browser other questions tagged

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