PDA

View Full Version : How can I read nested JSON objects.



jesus.valencia
23 Sep 2014, 7:43 PM
Hi experts,

I created a Store with nested JSON structures (let's call them Parent and Child). So far I can read the Root set, I actually have them displayed on a Grid, but I can't find a way to read the child objects of each parent. I did a console.log(record) -when clicking on one of the row's grid- in order to check -in Chrome- the selected record's child, I see in the log that the data object inside the record's constructor doesn't have its child objects. But in the raw object of the constructor I can see the child array and it's corresponding objects.

I have created two models, and associated them. I'm simplifying the model names and number of fields as follow:

Model 1:

Ext.define('ParentModel', {
extend: 'Ext.data.Model',
fields: [
'field1',
'field2'
],
hasMany: [{
name : 'child',
model : 'ChildModel',
associationKey : 'child'
}]
});


Model 2:

Ext.define('ChildModel', {
extend: 'Ext.data.Model',
fields: [
'childField1',
'childField2'
],
belongsTo: [{
name: 'child',
model: 'ParentModel',
associationKey: 'child'
}]
});


Store:


var data =
{
"parents" :
[{
"field1": "xyz",
"field2": "abc",
"child":
[
{
"childField1": "qwe",
"childField2": "asd"
},
{
"childField1": "rty",
"childField2": "fgh"
}
]
},{
"field1": "poi",
"field2": "lkj",
"child":
[
{
"childField1": "tgb",
"childField2": "cde"
}
]
}
]};
Ext.define( "myStore", {
extend : 'Ext.data.Store',
model : 'ParentModel',
data : data,
proxy : {
type: 'memory',
reader : {
type: 'json',
root: 'parents',
rootProperty: 'parents'
}
}
});


In this example, when selecting the first parent, I can see in that Parent record, the raw object has a Child array with 2 objects. The second Parent has also the Child array with one object. The data object has no Child array.

I can't seem to find a way to make it work. I validated the original JSON and it's ok.

The objective of the application is to have two views each one with two grids, the first view shows the list of "Parent" objects, when clicking on a row, the second view pop's up and show in the second grid the "Child" objects of the selected parent. At first I thought it was a mapping error in the second view, but then I checked the record and saw that there wasn't any child in the data object, only on the raw.

Please any advise is welcome.

Thanks in advance.

JV

jesus.valencia
24 Sep 2014, 5:38 PM
Duhhhhhh... In Model 1 I was missing something quite important, requiring the child model.




Ext.define('ParentModel', {
extend: 'Ext.data.Model',
requires: ['ChildModel'],
fields: [
'field1',
'field2'
],
hasMany: [{
name : 'child',
model : 'ChildModel',
associationKey : 'child'
}]
});


I can't believe all the time I struggled with this one. Hope this saves time to other people in distress.

Regards!