Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

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')
    ));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...