3 * Copyright(c) 2006-2009 Ext JS, LLC
5 * http://www.extjs.com/license
8 * @class Ext.data.JsonReader
9 * @extends Ext.data.DataReader
10 * <p>Data reader class to create an Array of {@link Ext.data.Record} objects from a JSON response
11 * based on mappings in a provided {@link Ext.data.Record} constructor.</p>
12 * <p>Example code:</p>
14 var Employee = Ext.data.Record.create([
15 {name: 'firstname'}, // map the Record's "firstname" field to the row object's key of the same name
16 {name: 'job', mapping: 'occupation'} // map the Record's "job" field to the row object's "occupation" key
18 var myReader = new Ext.data.JsonReader(
19 { // The metadata property, with configuration options:
20 totalProperty: "results", // the property which contains the total dataset size (optional)
21 root: "rows", // the property which contains an Array of record data objects
22 idProperty: "id" // the property within each row object that provides an ID for the record (optional)
24 Employee // {@link Ext.data.Record} constructor that provides mapping for JSON object
27 * <p>This would consume a JSON data object of the form:</p><pre><code>
29 results: 2, // Reader's configured totalProperty
30 rows: [ // Reader's configured root
31 { id: 1, firstname: 'Bill', occupation: 'Gardener' }, // a row object
32 { id: 2, firstname: 'Ben' , occupation: 'Horticulturalist' } // another row object
36 * <p><b><u>Automatic configuration using metaData</u></b></p>
37 * <p>It is possible to change a JsonReader's metadata at any time by including a <b><tt>metaData</tt></b>
38 * property in the JSON data object. If the JSON data object has a <b><tt>metaData</tt></b> property, a
39 * {@link Ext.data.Store Store} object using this Reader will reconfigure itself to use the newly provided
40 * field definition and fire its {@link Ext.data.Store#metachange metachange} event. The metachange event
41 * handler may interrogate the <b><tt>metaData</tt></b> property to perform any configuration required.
42 * Note that reconfiguring a Store potentially invalidates objects which may refer to Fields or Records
43 * which no longer exist.</p>
44 * <p>The <b><tt>metaData</tt></b> property in the JSON data object may contain:</p>
45 * <div class="mdetail-params"><ul>
46 * <li>any of the configuration options for this class</li>
47 * <li>a <b><tt>{@link Ext.data.Record#fields fields}</tt></b> property which the JsonReader will
48 * use as an argument to the {@link Ext.data.Record#create data Record create method} in order to
49 * configure the layout of the Records it will produce.</li>
50 * <li>a <b><tt>{@link Ext.data.Store#sortInfo sortInfo}</tt></b> property which the JsonReader will
51 * use to set the {@link Ext.data.Store}'s {@link Ext.data.Store#sortInfo sortInfo} property</li>
52 * <li>any user-defined properties needed</li>
54 * <p>To use this facility to send the same data as the example above (without having to code the creation
55 * of the Record constructor), you would create the JsonReader like this:</p><pre><code>
56 var myReader = new Ext.data.JsonReader();
58 * <p>The first data packet from the server would configure the reader by containing a
59 * <b><tt>metaData</tt></b> property <b>and</b> the data. For example, the JSON data object might take
66 totalProperty: 'results',
69 {name: 'job', mapping: 'occupation'}
71 sortInfo: {field: 'name', direction:'ASC'}, // used by store to set its sortInfo
72 foo: 'bar' // custom property
76 { 'id': 1, 'name': 'Bill', occupation: 'Gardener' },
77 { 'id': 2, 'name': 'Ben', occupation: 'Horticulturalist' }
81 * @cfg {String} totalProperty [total] Name of the property from which to retrieve the total number of records
82 * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
83 * paged from the remote server. Defaults to <tt>total</tt>.
84 * @cfg {String} successProperty [success] Name of the property from which to
85 * retrieve the success attribute. Defaults to <tt>success</tt>. See
86 * {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#exception exception}
87 * for additional information.
88 * @cfg {String} root [undefined] <b>Required</b>. The name of the property
89 * which contains the Array of row objects. Defaults to <tt>undefined</tt>.
90 * An exception will be thrown if the root property is undefined. The data packet
91 * value for this property should be an empty array to clear the data or show
93 * @cfg {String} idProperty [id] Name of the property within a row object that contains a record identifier value. Defaults to <tt>id</tt>
95 * Create a new JsonReader
96 * @param {Object} meta Metadata configuration options.
97 * @param {Array/Object} recordType
98 * <p>Either an Array of {@link Ext.data.Field Field} definition objects (which
99 * will be passed to {@link Ext.data.Record#create}, or a {@link Ext.data.Record Record}
100 * constructor created from {@link Ext.data.Record#create}.</p>
102 Ext.data.JsonReader = function(meta, recordType){
105 // default idProperty, successProperty & totalProperty -> "id", "success", "total"
108 successProperty: 'success',
109 totalProperty: 'total'
112 Ext.data.JsonReader.superclass.constructor.call(this, meta, recordType || meta.fields);
114 Ext.extend(Ext.data.JsonReader, Ext.data.DataReader, {
116 * This JsonReader's metadata as passed to the constructor, or as passed in
117 * the last data packet's <b><tt>metaData</tt></b> property.
122 * This method is only used by a DataProxy which has retrieved data from a remote server.
123 * @param {Object} response The XHR object which contains the JSON data in its responseText.
124 * @return {Object} data A data block which is used by an Ext.data.Store object as
125 * a cache of Ext.data.Records.
127 read : function(response){
128 var json = response.responseText;
129 var o = Ext.decode(json);
131 throw {message: "JsonReader.read: Json object not found"};
133 return this.readRecords(o);
136 // private function a store will implement
137 onMetaChange : function(meta, recordType, o){
144 simpleAccess: function(obj, subsc) {
151 getJsonAccessor: function(){
153 return function(expr) {
155 return(re.test(expr)) ?
156 new Function("obj", "return obj." + expr) :
166 * Create a data block containing Ext.data.Records from a JSON object.
167 * @param {Object} o An object which contains an Array of row objects in the property specified
168 * in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
169 * which contains the total size of the dataset.
170 * @return {Object} data A data block which is used by an Ext.data.Store object as
171 * a cache of Ext.data.Records.
173 readRecords : function(o){
175 * After any data loads, the raw JSON data is available for further custom processing. If no data is
176 * loaded or there is a load exception this property will be undefined.
182 this.meta = o.metaData;
183 this.recordType = Ext.data.Record.create(o.metaData.fields);
184 this.onMetaChange(this.meta, this.recordType, o);
186 var s = this.meta, Record = this.recordType,
187 f = Record.prototype.fields, fi = f.items, fl = f.length, v;
189 // Generate extraction functions for the totalProperty, the root, the id, and for each field
190 this.buildExtractors();
191 var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
193 v = parseInt(this.getTotal(o), 10);
198 if(s.successProperty){
199 v = this.getSuccess(o);
200 if(v === false || v === 'false'){
206 for(var i = 0; i < c; i++){
208 var record = new Record(this.extractValues(n, fi, fl), this.getId(n));
215 totalRecords : totalRecords
220 buildExtractors : function() {
224 var s = this.meta, Record = this.recordType,
225 f = Record.prototype.fields, fi = f.items, fl = f.length;
227 if(s.totalProperty) {
228 this.getTotal = this.getJsonAccessor(s.totalProperty);
230 if(s.successProperty) {
231 this.getSuccess = this.getJsonAccessor(s.successProperty);
233 this.getRoot = s.root ? this.getJsonAccessor(s.root) : function(p){return p;};
234 if (s.id || s.idProperty) {
235 var g = this.getJsonAccessor(s.id || s.idProperty);
236 this.getId = function(rec) {
238 return (r === undefined || r === "") ? null : r;
241 this.getId = function(){return null;};
244 for(var i = 0; i < fl; i++){
246 var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
247 ef.push(this.getJsonAccessor(map));
252 // private extractValues
253 extractValues: function(data, items, len) {
255 for(var j = 0; j < len; j++){
257 var v = this.ef[j](data);
258 values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue, data);
264 * Decode a json response from server.
265 * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]
266 * @param {Object} response
268 readResponse : function(action, response) {
269 var o = (response.responseText !== undefined) ? Ext.decode(response.responseText) : response;
271 throw new Ext.data.JsonReader.Error('response');
273 if (Ext.isEmpty(o[this.meta.successProperty])) {
274 throw new Ext.data.JsonReader.Error('successProperty-response', this.meta.successProperty);
276 // TODO, separate empty and undefined exceptions.
277 if ((action === Ext.data.Api.actions.create || action === Ext.data.Api.actions.update)) {
278 if (Ext.isEmpty(o[this.meta.root])) {
279 throw new Ext.data.JsonReader.Error('root-emtpy', this.meta.root);
281 else if (o[this.meta.root] === undefined) {
282 throw new Ext.data.JsonReader.Error('root-undefined-response', this.meta.root);
285 // make sure extraction functions are defined.
286 this.ef = this.buildExtractors();
292 * @class Ext.data.JsonReader.Error
293 * Error class for JsonReader
295 Ext.data.JsonReader.Error = Ext.extend(Ext.Error, {
296 constructor : function(message, arg) {
298 Ext.Error.call(this, message);
300 name : 'Ext.data.JsonReader'
302 Ext.apply(Ext.data.JsonReader.Error.prototype, {
304 'response': "An error occurred while json-decoding your server response",
305 'successProperty-response': 'Could not locate your "successProperty" in your server response. Please review your JsonReader config to ensure the config-property "successProperty" matches the property in your server-response. See the JsonReader docs.',
306 'root-undefined-response': 'Could not locate your "root" property in your server response. Please review your JsonReader config to ensure the config-property "root" matches the property your server-response. See the JsonReader docs.',
307 'root-undefined-config': 'Your JsonReader was configured without a "root" property. Please review your JsonReader config and make sure to define the root property. See the JsonReader docs.',
308 'idProperty-undefined' : 'Your JsonReader was configured without an "idProperty" Please review your JsonReader configuration and ensure the "idProperty" is set (e.g.: "id"). See the JsonReader docs.',
309 'root-emtpy': 'Data was expected to be returned by the server in the "root" property of the response. Please review your JsonReader configuration to ensure the "root" property matches that returned in the server-response. See JsonReader docs.'