Search code examples
jsoncakephp-2.0responseoutput

CakePHP jSon format change


I'm finding list of Areas for my CakePHP 2.x website and it supports, JSON output as below with find all method:

$this->Area->find('all', array('fields' => array('id', 'name', 'order'), 'conditions' => array('Area.status' => 1)));

Below is my JSON output:

[{"Area":{"id":"2","name":"Area 1","order":"1"}},{"Area":{"id":"3","name":"Area 2","order":"1"}}]

Now Is that possible for me to remove Area tag which is repeating everytime?

Any patch for same? Do let me know if any suggestions / ideas.


Solution

  • CakePHP Provides some in-built library functions for data extraction from result set and output same as JSON format.

        // initialize your function to render false and response type json
        $this->autoRender = false; // no view to render
        $this->response->type('json');
    
        // Remove Area from array and encode
        $area = Set::extract('/Area/.', $area);
        $json = json_encode( $area);
        $this->response->body($json);
    

    Hope it helps !