View Full Version : Optional JSON elements in grids

Tim Siney
9 Apr 2010, 1:05 AM

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,
"id": 202,
"optional": null,

9 Apr 2010, 3:53 AM
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+' : "";') :
return obj[expr];
} catch(e){}
return Ext.emptyFn;

9 Apr 2010, 7:25 AM
cool one!