Customizing JSON output CakePHP

1.7k views Asked by At
    $user = $this->User->find( 'all' );
    $this->set( 'users', $user );

I have this code in my controller.

In my view I have this.

echo json_encode( compact( 'users' ) );

It outputs json like this

    {
    "users": [{
        "User": {
            "user_id": "2",
            "email": "[email protected]",
            "name": "Blah"
        }]
    }
}

Is there anyway to format this to remove the entire array wrapped in "users", and also remove every object being a member of "User".

This makes it harder to use on the front end. I'd like it to look like this.

[{
    "user_id": "2",
    "email": "[email protected]",
    "name": "Blah"
}]

Thanks for any help.

2

There are 2 answers

0
ndm On BEST ANSWER

I don't fully understand what you mean by "remove the entire array wrapped in "users"" and "remove every object being a member of "User"", but according to your desired output format example, you'll need to extract and pass the exact data that you want to be encoded to json_encode, instead of passing everything using compact.

Extracting could be done with the Set or the Hash class (depending on your Cake version)

Assuming your model returns the data in the default CakePHP format, this for example:

json_encode(Set::extract('/User/.', $users));

should give you a structure like this:

[{
    "user_id": "2",
    "email": "[email protected]",
    "name": "Blah"
}]

and with multiple users it should look like this

[{
    "user_id": "1",
    "email": "[email protected]",
    "name": "Bar"
},
{
    "user_id": "2",
    "email": "[email protected]",
    "name": "Blah"
}]
0
Aditya P Bhatt On

Use like this:

$users= (Set::extract('/User/.', $users));
pr($users);

It will remove Model from result Array and then json_encode or whatever further usage.

More library functions Set class Here and Hash class Here