0

What is the simplest and best practice way to customise the JSON output in cakephp 2.x.

I have the following in my controller:

$questions = $this->Question->find('threaded', array(
  'fields' => array(
    'label',
    'id',
    'parent_id',
    'load_on_demand'
   ),
  'order' => array('lft ASC') 
));

$questions= $this->set('questions', $questions);

$this->set('_serialize', 'json');

I have the following JSON (truncated);

{
    "Question": {
        "id": "27",
        "parent_id": "0",
        "load_on_demand": "true",
        "label": "Main Menu"
    },
    "children": [
        {
            "Question": {
                "id": "28",
                "parent_id": "27",
                "load_on_demand": "true",
                "label": "Web Development"
            },

but I need it to be like the following example in jqTree;

{
    label: 'node1',
    children: [
        { label: 'child1' },
        { label: 'child2' }
    ]
},
{
    label: 'node2',
    children: [
        { label: 'child3' }
    ]
}

2 Answers 2

3

Just use the Hash class before setting the results:

function buildQuestion(){

$questions = $this->Question->find('all', array(
  'fields' => array('label', 'id', 'parent_id','load_on_demand'),
  'order' => array('lft ASC')
));

 $results = Hash::extract($questions, '{n}.Question');
 $results = Hash::nest($results, ['idPath' => '{n}.id', 'parentPath' => '{n}.parent_id');
Sign up to request clarification or add additional context in comments.

Comments

0

First of all, you shouldn't use find for these custom labeling or Rest api code. its simply because using any ORM might fetch extra data/object to that api, consuming lots of memory for bulk requests. Use sql like :

Select `Question`.`id` as `id`, .....
from `Question`
INNER JOIN `children` on `children`.`parent_id` = `Question`.`id`
where .......
//I cant say much about the query as the model aint clear to me

This might help if you want to add extra field. remember to alias the fields needed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.