PDA

View Full Version : JsonParser mapping problem



spaque99
5 Jun 2008, 9:19 AM
Hello all,

When using the JsonParser with a record that has mapping in it, I have a problem where an exception gets thrown when a property does not exist in my json... For example if my record is:



var rec = Ext.data.Record.create([{
name:'prop1'
},{
name:'prop2',
mapping:'lvl2.prop2'
]);
This is fine when my json is


{
records: [ {
prop1: 'v1',
lvl2: {
prop2: 'v2'
}
},
...
]
}
But if I have a json that does not have this lvl2 property like this:

This is fine when my json is


{
records: [ {
prop1: 'v1',
lvl2: {
prop2: 'v2'
}
}, {
prop1: 'v3'
}
]
}
I get a problem with the jsonAccessor returned by the getJsonAccessor of the JsonParser because it can't find lvl2.prop2.

I think it would be better if we could make the reader set an undefined value to the prop2 in the returned record than making it break there...

To do that, I have overriden the getJsonAccessor method from the JsonParser class by this code:



getJsonAccessor: function(){
var re = /[\[\.]/;
return function(expr) {
try {
return(re.test(expr))
? new Function("obj", "try{ return obj." + expr + "} catch(e) { return undefined }")
: function(obj){
return obj[expr];
};
} catch(e){}
return Ext.emptyFn;
};
}()
The modified part is in bold.

Any comments from the Ext team or anyone else?

Thanks
Seb

devnull
5 Jun 2008, 9:32 AM
this is basic javascript stuff. if you make an object and then try to access a nonexistent property of that object, javascript will error.
you should make sure all used properties are always accessible in your data, even if they contain null or blank values.
adding code such as you provide creates uneccessary overhead in a function that is run many times.

spaque99
5 Jun 2008, 9:36 AM
I understand that part, but you don't always control what is returned back in the json response of an ajax call... and even if you do control it, you may have scenarios where you do not want to set any values for it and wanted to reduce the amount of data returned to reduce traffic...