Domingo C. Domingo C. - 3 months ago 5
JSON Question

How to output serialized JSON view data as an array of objects, instead of wrapped in an outer object?

I am converting the returning value of CakePHP array to JSON, currently its like this:

{
"platformusers" : [
{
"id" : "1",
"name" : "user1"
},
{
"id" : "3",
"name" : "user3"
}
]
}


And I want it to be like this:

[
{
"id" : "1",
"name" : "user1"
},
{
"id" : "3",
"name" : "user3"
}
]


I am trying with Set::extract('{n}.Model', $data) Hash::extract('{n}.Model', $data) with no luck at all.

Full code:

$platformusers = $this->Platformuser->find('all', array(
'fields' => array('Platformuser.id', 'Platformuser.name')
));

$platformusers = Hash::extract('{n}.Platformuser', $platformusers);

$this->set(array(
'platformusers' => $platformusers,
'_serialize' => array('platformusers')
));

ndm ndm
Answer

Set a string for the _serialize option instead of an array. An array indicates that there might be multiple view vars that need to be serialized, and that requires them to be packed into separate object properties.

$this->set(array(
    'platformusers' => $platformusers,
    '_serialize' => 'platformusers'
));

That should give you the desired result.