While working on a project we faced the need to sync data between the browser and the server in JSON format, most of these data are ActiveRecord(s), after some search we found "ejsonbehavior" ... it is really a cool extension but unfortunately the output was not as we expected, so we decided to extend the capabilities of the CJSON to allow traversing ARs relations
Requirements ¶
Developed and tested under Yii 1.1.13
Usage ¶
Simply
NJSON::encode(SomeModel::model()->with('relation', 'relation.deep_relation')->findAll());
Key with numeric name
Hi, we found a little bug in the function "nameValue" when you serialize in key=>values an array, if the key is an numeric value the extensión serialize like a number and create an invalid JSON, for now we solved this using this:
protected static function nameValue($name, $value) { //return self::encode(strval($name)) . ':' . self::encode($value); // The Keys must be enclose with quotes return '"'.strval($name).'" :' . self::encode($value); }
You made a Great work ;-)
Cheers from Argentina
Re: Key with numeric name
Thanks for trusting my code ...
Re: Re: Key with numeric name
Hi Amr, we are storing an array with numerical keys into an attibute, we use your extension to serialize this model and and sending trough ajax
this is an example:
Filter
First of all, thanks! I really liked your extension!
I was using CArJSON (http://www.yiiframework.com/extension/carjson/) and it has an option to filter model/relations columns. Is it possible to do something like it?
Thanks
Re: Filter
Actually not at this moment but I can add it ... hopefully soon
Re: Re: Filter
Try jsonize
Filtering using CArJSON usage example:
Yii::app()->jsonize; $users = User::model()->with('votes')->findAll($criteria); echo jsonizenc($users); // all attributes and loaded relations ('votes' in this example) are processed echo jsonizenc($users, array('posts','comments')); // all attributes are processed, specified relations and loaded ones ('posts','comments' and 'votes') are processed echo jsonizenc($users, array('posts','comments'), true); // all attributes are processed, but only specified relations ('posts','comments') are processed echo jsonizenc($users, array('id', 'username', 'email', 'first_name', 'last_name', 'posts' => array( 'id', 'author_id', 'content' ), 'comments' => array( 'id', 'author_id', 'content' ), 'votes' => array( /* attributes here */)) ), true, true); // only specified attributes and relations are processed
great work
Thanks a lot.
Re: great work
You are welcome :)
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.