Read values from a Json structure using Jquery

1

I am trying to read the data that is received via php and I need to read those values separately. The return is a json object, when I show in the console using the command console.log(data) and the following structure appears:

{"clientes":[
   {"idEntidade":"314","nmEntidade":"3D Inform\u00e1tica Ltda"}, 
   {"idEntidade":"439","nmEntidade":"Academia BigBone Fitness"}, 
   {"idEntidade":"308","nmEntidade":"Academia de Ginastica Forca e Saude Ltda - ME"},
   {"idEntidade":"371","nmEntidade":"Academia Simetria"}
]}

But if I try to access a position with the command console.log(data[0]['nmEntidade']) for example, the answer is undefined .

Jquery Code

    $.getJSON('../caminho/do/json', function (data) {
        console.log(data);
        console.log(data[0]['nmEntidade']);
    });

PHP method that returns the data. (I am using the framework Symfony )

public function filtraClienteAction()
{        
    $em = $this->getDoctrine()->getManager();
    $connection = $em->getConnection();
    $statement = $connection->prepare("SELECT idEntidade, nmEntidade FROM entidades ORDER BY nmEntidade");
    $statement->execute();
    $clientes = $statement->fetchAll();

    $response = new JsonResponse(json_encode(array(
        'clientes' => $clientes
    )));
    $response->headers->set('Content-Type', 'application/json');

    return $response;

}
    
asked by anonymous 15.05.2018 / 15:32

3 answers

1

You will be able to access like this:

console.log(data['clientes'][0]['nmEntidade']);
    
15.05.2018 / 15:38
2

You are accessing wrong, the correct thing is to inform the object before and its position after the case is 0, you have to access the object that is client before.

$.getJSON('teste.json', function (data) {
    console.log(data);
    console.log(data.clientes[0]['nmEntidade']);
});
    
15.05.2018 / 15:41
0

I was able to solve by creating the following structure:

    $.getJSON('../caminho/do/json', function (data) {
        var clientes = JSON.parse(data);
        console.log(clientes['clientes'][0]['nmEntidade']);
    });
    
15.05.2018 / 15:50