PDA

View Full Version : Support for custom JSON encoding


Condor
07-10-2009, 07:09 AM
JSON encode currently always encodes objects the same way and there is no way to influence the behavior.

I would like to suggest supporting a toJSON method for objects that is used to JSON encode the object (if present).

Override:
(function(){
var encode = Ext.encode;
Ext.encode = Ext.util.JSON.encode = function(o){
if(o && typeof o.toJSON == 'function'){
return o.toJSON();
}
return encode(o);
};
})();

Example usage:
Ext.override(Ext.data.Store, {
toJSON: function(){
var data = [];
for(var i = 0, len = this.getCount(); i < len; i++){
data.push(this.getAt(i).data);
}
return Ext.encode(data);
}
});
(normally encoding a store would result in a too much recursion error (http://extjs.com/forum/showthread.php?t=73908))

Animal
07-10-2009, 08:26 AM
Very good idea.

jgarcia@tdg-i.com
07-10-2009, 11:06 AM
JSON encode currently always encodes objects the same way and there is no way to influence the behavior.

I would like to suggest supporting a toJSON method for objects that is used to JSON encode the object (if present).

Override:
var encode = Ext.encode;
Ext.encode = Ext.util.JSON.encode = function(o){
if(o && typeof o.toJSON == 'function'){
return o.toJSON();
}
return encode(o);
};

Example usage:
Ext.override(Ext.data.Store, {
toJSON: function(){
var data = [];
for(var i = 0, len = this.getCount(); i < len; i++){
data.push(this.getAt(i).data);
}
return Ext.encode(data);
}
});
(normally encoding a store would result in a too much recursion error (http://extjs.com/forum/showthread.php?t=73908))
fixed ;)

jgarcia@tdg-i.com
07-10-2009, 11:07 AM
btw, +1.

mystix
07-11-2009, 04:24 AM
+1

hendricd
07-11-2009, 08:20 AM
Indeed, +1.