PDA

View Full Version : Optional JSON elements in grids



Tim Siney
9 Apr 2010, 1:05 AM
Hi,

I have a JSON string which contains optional elements. When I render the JSON in a grid, the pages where all records contain the optional element will render correctly, however, when there are records which do not contain it, no output is rendered. I am referencing the object in my field mapping using the code below:


{name: 'name', mapping: 'optional.name', type: 'string'}

I understand why this is not working as I imagine Ext is trying to reference a JSON element that doesn't exist. However, taking the following source JSON, how can I reference the "name" property of the "optional" object in such a way that it will allow records where the "optional" object is null?


{"totalCount":1, "objects":[
{
"id": 202,
"optional":{"name":"test"}
},{
"id": 202,
"optional": null,
}
]}

hendricd
9 Apr 2010, 3:53 AM
@Tim--
This override might provide some relief. It asserts the nested reference and returns an empty string for your scenario.


Ext.override(Ext.data.JsonReader, {

createAccessor : function(){
var re = /[\[\.]/;
return function(expr) {
try {
return(re.test(expr)) ?
// Be more careful with createAccessor, test the mapping first before using it.
new Function('obj', 'return (obj["'+expr+'".split(".")[0]]) ? obj.'+expr+' : "";') :
function(obj){
return obj[expr];
};
} catch(e){}
return Ext.emptyFn;
};
}()
});

steffenk
9 Apr 2010, 7:25 AM
cool one!