PDA

View Full Version : Configuration of JsonReader - root: as the "real root" of data?



antonye
21 Jun 2010, 1:34 AM
Quick question - I think I know the answer to this one, but just want to check with someone who has more experience with ExtJS and JSON than I do!

I have a JsonReader, which is working fine, but I want to expand the scope of the data that it reads; the reason being that my data returned looks something like this:



{
errors: null,
success: true,
a: {
somedata: blah,
moredata: blah
},
b: {
anothernode: blah,
yetmoredata: blah
},
c: {
etcetc: blah,
etcetcetc: blah
}
}


So when I bind my JsonReader as "root: a" this works fine, and I can read self.getAt(0).get('somedata') without any problems at all.

But I want to expand the scope of my reader so that I can also read the nodes "b" and "c" as well.

Obviously what I want to be able to do is to bind the "root:" to ... well, the root of the JSON data returned, but I'm scratching my head because (a) the API says I have to bind it to *something* and (b) it doesn't like "root: '' " or combinations of empty/null to that effect!

So is it possible to bind the JsonReader.root to the root of my JSON data, or do I need to encapsulate my current JSON data model within another level so that I can then bind it to this new root, eg:



{
errors: null,
success: true,
newroot: {
a: {
somedata: blah,
moredata: blah
},
b: {
anothernode: blah,
yetmoredata: blah
},
c: {
etcetc: blah,
etcetcetc: blah
}
}
}


Like I said, I think I know the answer to this one, so I guess I'm looking for confirmation ;)

Condor
21 Jun 2010, 2:43 AM
No need to modify your data. You only have to specify a special function for the root that extracts the data as an array, e.g.

root: function(data){
var result = [];
for(var prop in data){
if(data.hasOwnProperty(prop) && Ext.isObject(data[prop]){
result.push(Ext.apply({id: prop}, data[prop]);
}
}
return result;
}
(only works on Ext 3.2+)

antonye
21 Jun 2010, 2:47 AM
Awesome, thankyou!

I was wondering if there would be some way of implementing a customised root (I had read about swapping the root in a pre-forum-post search!) but my inexperience in ExtJS was holding me back.