javascript – Access JSON with multiple objects in JS

Question:

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": "Teste@Teste.com",
      "ddd": "41",
      "telCelular": "(41)123456789",
      "telResidencial": "123456789",
      "telComercial": "12345-6789"
    }
}
]

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

(JSON is received via $.get)

Answer:

You are receiving your .json file in text format from the server. The best way to solve this is to change your code on the server to send the .json file with the proper header . In PHP it would look 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() the jQuery itself will do the appropriate conversion and return you a JavaScript object.


Now, if you don't have access to the server code that sends the .json file, just do the conversion inside the $.get() JSON.parse() function using the JSON.parse() function, which 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); // "Teste@Teste.com"
     }
   }
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Scroll to Top