Placing JSON string into a store

2019-08-30 19:05发布

Simple question here. How could I place this JSON string into an Ext.data.Store?

   {
   "elements":[
      {
         "element":{
            "name":"value 1",
            "id":"element 1",
            "attributes":[
               {
                  "attrname":"id",
                  "attrvalue":"This is the ID"
               },
               {
                  "attrname":"name",
                  "attrvalue":"This is the name"
               },
               {
                  "attrname":"description",
                  "attrvalue":"This is the description"
               },
               {
                  "attrname":"table_name",
                  "attrvalue":"This is the table"
               }
            ]
         }
      }
   }

This is a simplified version of my question: Placing JSON response elements into a store- Ext JS

Cheers!

标签: json Extjs
1条回答
Evening l夕情丶
2楼-- · 2019-08-30 19:25

Since the JSON is coming back from the server, the first thing you'll need to do is to deserialize it from a JSON-formatted string into an object that you can navigate. Assuming that it's valid JSON, you can simply do this by using Ext.decode().

This will give an object that has an array of objects at the "elements" key. Simply loop over the elements array and create a new model instance that can be inserted into your store.

Here's a link to a live example: https://fiddle.sencha.com/#fiddle/3u6

And here's the code from that example:

var data = YOUR_DATA_HERE,
var store = Ext.create('Ext.data.Store', {
    fields: ['id', 'name', 'description', 'table_name'],
    proxy: {
        type: 'memory'
    }
})
Ext.create('Ext.grid.Panel', {
    title: 'Test Data',
    store: store,
    columns: [{
        text: 'ID',
        dataIndex: 'id'
    }, {
        text: 'Name',
        dataIndex: 'name'
    }, {
        text: 'Description',
        dataIndex: 'description'
    }, {
        text: 'Table Name',
        dataIndex: 'table_name'
    }],
    renderTo: Ext.getBody()
});
var decoded = Ext.decode( data );
// loop over decoded data
for( var i=0; i<decoded.elements.length; i++ ) {
    var element = decoded.elements[ i ].element;
    // set implicit model
    var model = {};
    // loop over attributes
    for( var x=0; x<element.attributes.length; x++ ) {
        var attribute = element.attributes[ x ];
        model[ attribute.attrname ] = attribute.attrvalue;
    }
    // implicitly cast data as Model
    store.add( model );
}
查看更多
登录 后发表回答