Iwould Preferanon Mon Jun 21 10:44:09 -0400 2010

Subject: JSON Encoding of Results

I was wondering if there might be a way to easily encode the results from a finder that returns an array vs. just iterating over the array and adding each object to said array. For example:

$temp = Test::find_all_by_id (1);
encode_json ($temp);

The problem with the above code is it displays something along the lines of:


and in the case of an array of objects as the return, you get something along the lines of:


instead of dumping the model's attributes. What I invariably end up doing is creating a temporary array, adding each object to the array using to_json (), and then calling json_encode() on the array.

Being only moderately familiar with the inner workings of json_encode() when dealing with objects, or arrays of objects, I thought, perhaps, there may be some function that could be overloaded to handle the object's serialization.

Just a thought.

Thanks for all your hard work on this project.

Iwould Preferanon Mon Jun 21 11:27:41 -0400 2010

Just a quick update on this. After diving into the inner workings of json_encode(), it's probably not possible to do this. This method doesn't seem to provide any way to overload a method to do the encoding in the class itself; it just iterates over the public members.

Kien La Mon Jun 21 11:43:11 -0400 2010

Ideally what we've wanted to do is Test::find_all_by_id(1)->to_json(). This would be possible if we used ArrayObjects instead of raw arrays. Using ArrayObjects would allow us to extend from it and add some serialization code there but there's a performance hit in using ArrayObjects for everything. We're not sure that we want to take that performance hit just yet for something like this. There is another option I've been thinking of but yes ultimately something like this will be supported in a future version.

peter z Thu Aug 04 10:36:22 -0400 2011

Has there been any progress on this? JSON-encoding array of models is royal pain right now, I essentially have to build JSON string by hand.