Search code examples
javascriptjsonextjsextjs-chart

How to parse a response from extjs proxy?


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?


Solution

  • 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
                }
            }
        },});