Formatting JSON in cakephp

Asked

Viewed 150 times

1

I’m generating a json from a find in Cakephp.

Controller:

    public function listar() {
        $this->layout = 'ajax';
        $this->set('resultados', $this->Sala->listarSala());
    }

Model:

    public function listarSala() {
    $options = array(
        'fields' => array(
            'Sala.id', 'Sala.nome', 'Sala.data', 'Sala.inicio', 'Sala.fim'
        ),
        'conditions' => array(
            'Sala.data >= curdate()',
        ),
        'order' => array(
            'Sala.data ASC',
            'Sala.inicio ASC'
        ),
        'limit' => 50
    );
    return $this->find('all', $options);
}

View:

<?php
echo json_encode($resultados);

But when I visualize the answer, I get the following result:

[
{"Sala":{"id":"47","nome":"Grupo","data":"15\/05\/2014","inicio":"09:30:00","fim":"11:00:00"}},
{"Sala":{"id":"48","nome":"Grupo","data":"29\/05\/2014","inicio":"09:30:00","fim":"11:00:00"}},
{"Sala":{"id":"49","nome":"Grupo","data":"12\/06\/2014","inicio":"09:30:00","fim":"11:00:00"}}
]

I noticed that it creates a room(model) object and inside it the properties searched in Mysql.

My question is the following, how could I make Cakephp return this result without the room object, with the normal json notation, or would that be so? What would be the right way?

2 answers

1

You need to format the array return of Cakephp so that json is presented in the correct way.

In your case you need to descend a level on array.

Leave your view as follows:

<?php
foreach ($resultados as $sala) {
    $salas[] = $sala["Sala"];
}
echo json_encode($salas);
  • 1

    This way it worked: <?php&#xA;foreach ($resultados as $sala) {&#xA; $salas[] = $sala["Sala"];&#xA;}&#xA;echo json_encode($salas);

  • But that’s not exactly what I intended, I wanted a way that this result already came from cake.

  • "Room" in cake represents the model you are using and the normal is that it always tells you that, part of the framework conventions. This helps in future code maintenance

0

Cake informs that you can return a Response this way is just pass the object or the list of objects within the example below

public function listar() {
    $this->layout = 'ajax';
    //$this->set('resultados', $this->Sala->listarSala());
    $salas = $this->Sala->listarSala();
    $response = $this->response->withType('application/json')
        ->withStringBody(json_encode(['salas' => $salas]));   
    return $response;     
}

Browser other questions tagged

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