How to parse a response from extjs proxy?

2.7k Views Asked by At

I am receiving a json object as a response from a webservice who's format is similar to:-

      {
         studentData:[
            {
                "history":25,
                 "science":69,
                 "maths":45
            }
           ]
      }

I am using the following following code to read the JSON:-

Ext.define('MyStore.store.dashboard.graphs.Temp', {
extend: 'Ext.data.Store',
 proxy: {
        type: 'ajax',
        url: 'abc.php', 

        headers: {
            'Content-Type': 'application/json'
        },

         reader: {
                type: 'json',
                rootProperty: 'studentData',

                listeners: {

                    exception: function(reader, response, error, eOpts) {
                        console.log('YT reader exception');
                        console.log(error.message, error);
                        console.log(response);
                    }

                }
            }

Can i parse the JSON response so that it is stored in the following format?

     {
         studentData:[
            {
                "subject":"History",
                 "marks":"25"    
            },
           {
                 "subject":"Maths",
                 "marks":"25"
           }
           ]
      }

I need to show these values in a chart having xfield as subject and yfield as marks. Is there a listener i can append to the proxy so that i can modify the store structure according to my requirement?

2

There are 2 best solutions below

0
Saloo On BEST ANSWER

Depending on the version of ExtJS you are using , you can change the JSON data before the store loads it.

ExtJS 4 - You can create your own reader class by extending Ext.data.reader.Reader class and override the getResponseData(response) and change the json and return the ResultSet.

ExtJS 5 - You can use transform feature of Reader class and can change the response data object.

    Ext.create('Ext.data.Store', {
    model: 'User',
    proxy: {
        type: 'ajax',
        url : 'users.json',
        reader: {
            type: 'json',
            transform: {
                fn: function(data) {
                    // do some manipulation of the raw data object
                    return data;
                },
        scope: this
            }
        }
    },});
0
CD.. On

You can use a transform function in your reader:

If a transform function is set, it will be invoked just before readRecords executes. It is passed the raw (deserialized) data object. The transform function returns a data object, which can be a modified version of the original data object, or a completely new data object. The transform can be a function, or a method name on the Reader instance, or an object with a 'fn' key and an optional 'scope' key.