HTML5 Zone is brought to you in partnership with:

Gary Sieling is a software developer interested in dev-ops, database technologies, and machine learning. He has a computer science degree from the Rochester Institute of Technology. He has worked on many products in the legal and regulatory industries, having worked on and supported several data warehousing applications. Gary is a DZone MVB and is not an employee of DZone and has posted 62 posts at DZone. You can read more from them at their website. View Full User Profile

ExtJs JSON Reader Example

05.10.2013
| 4621 views |
  • submit to reddit

I received the following email from a reader:

Thank you very much for finding time to read my mail. I came across your blog http://garysieling.com/blog/extjs-pie-chart-example It would be greatly helpful, if you could provide me with the code of binding the data dynamically to the DS. I have already generated the data in JSON format via Servlet:

{“success”:true,”campaignList”:[{"NumberOfCampaigns":1,"CamapaignScheduleDate":"Mar 23, 2013 12:00:00 AM"}]}

How do I attach this here..

var store = Ext.create(‘Ext.data.Store’, {
    model: ‘PopulationPoint’,
    data: MY_DATA
  });

Any help would be of great use. Thanks and regards

Response:

There are a couple ways to approach this problem. The linked example that I wrote uses a raw Javascript object to render a pie chart. Lets say your servlet returns JSON in a variable – you could parse this yourself and use the result in the store, but Ext provides the JSONReader for this purpose:
var store = new Ext.data.JsonStore({
    url: '/servlet',
    root: 'campaignList',
    fields: [{name:'NumberOfCampaigns', type: 'int'},
             {name:'CampaignScheduleDate', type:'date'}]
});
A couple things to note here- this assumes you know the types in advance, and in particular, you want to test dates carefully to make sure you render them in a format Ext can parse.  If needed, you can specify a date format as well, like so: dateFormat: ‘m-d-Y g:i A’

You can add a “mapping” to the fields, to alias columns from the servlet. The root value is optional – if a servlet returns a raw array this is not necessary. You may need to add “totalProperty” to the store as well – this specifies the name of a property in the JSON payload which specifies the total number of records. This is only needed for paging scenarios, where not all the results are returned at once.



Published at DZone with permission of Gary Sieling, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)