Read values from a Json structure using Jquery

Asked

Viewed 159 times

1

I’m trying to read the data that is received via php and I need to read these values separately. Return is an object json, when I show on console using 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’m 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;

}

3 answers

2

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

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

1


You’ll be able to access it like this:

console.log(data['clientes'][0]['nmEntidade']);

0

I managed to solve by creating the following structure:

    $.getJSON('../caminho/do/json', function (data) {
        var clientes = JSON.parse(data);
        console.log(clientes['clientes'][0]['nmEntidade']);
    });
  • Accept one of the answers Diego to close the question on the site.

Browser other questions tagged

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