Formatting JSON in cakephp

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 view 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 object (model) and within it the properties searched for in MySql.

My question is as follows, how could I make CakePhp return this result without the room object, with the normal jSon notation, or would it be anyway? What would be the correct way?

    
asked by anonymous 09.05.2014 / 14:18

2 answers

1

You need to format the CakePhp return array so that jSon is displayed correctly.

In your case you need to go down one level in array .

Leave your view as follows:

<?php
foreach ($resultados as $sala) {
    $salas[] = $sala["Sala"];
}
echo json_encode($salas);
    
09.05.2014 / 14:32
0

Cake informs that it can return a Response in this way, just pass the object or 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;     
}
    
20.12.2017 / 12:07