Access JSON with multiple objects in JS

Posted on

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": "",
      "ddd": "41",
      "telCelular": "(41)123456789",
      "telResidencial": "123456789",
      "telComercial": "12345-6789"

and I wanted to access the data with JS
I usually make a for(i in response.content) and I access it with response.content[i].nome
but I can not. It is 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 resolve this is to change your code on the server to send the .json file with the appropriate header . In PHP it would look something like this:

$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 do the proper conversion and return you a JavaScript object.

Now, if you do not have access to the server code that sends the .json file, just do the conversion within the $.get() function using the

Leave a Reply

Your email address will not be published. Required fields are marked *