CJSON output should not include columns not queried

Another issue with CJSON is that it will output all fields (attributes) in the table even if they were not queried.

For example a table User with columns







If I did this:

$criteria=new CDbCriteria;

$criteria->select = "id, user, birthday";

$criteria->order = "birthday";

$users = User::model()->findAll($criteria);

$this->layout = false;


the output would look something like this:

(I made up the date format)

[{"id":"1", "user":"Jack", "password":null, "group":null, "email":null, "birthday":"10-dec-1960"},

{"id":"2", "user":"Jill", "password":null, "group":null, "email":null, "birthday":"12-dec-1965"}]

instead of just:

[{"id":"1", "user":"Jack", "birthday":"10-dec-1960"},

{"id":"2", "user":"Jill", "birthday":"12-dec-1965"}]

it includes all columns even if they were not queried and gives the ones not queried a value of null.

the problem with this is

  • The JSON output is longer than needed. Waste of bandwidth, especially if there are lots of columns on the table

  • I think it might not be good for security. Can easily see the names of all columns in the table

I think this is a big problem with CJSON. Right now because of this (and the other issue about not supporting related models) I have to manually convert the CActiveRecords to a standard php array including only the fields queried before doing a CJSON::encode on it.

just add something like this:


to select only the columns you want see api:


If you look at my example above, I'm already doing that.

The problem is not that the query is returning additional columns, it is that CJSON is outputting more columns than what was actually queried.

It is not the responsibility of CJSON to understand data models. You could have a method in your model to return the fields you need as an array and encode those.

Cheers, Wei.

Agree with Wei. You can use getAttributes() to retrieve the needed attribute values.

chanon you are right  I was too blind to see "your" problem.

I did the same what wei mentioned with the code below:

regards Horizons