Ext JS 4.0.7 Sencha Docs

Ext.data.reader.Json

Alternate names

Ext.data.JsonReader

Hierarchy

Ext.Base
Ext.data.reader.Reader
Ext.data.reader.Json

Subclasses

Files

The JSON Reader is used by a Proxy to read a server response that is sent back in JSON format. This usually happens as a result of loading a Store - for example we might create something like this:

Ext.define('User', {
    extend: 'Ext.data.Model',
    fields: ['id', 'name', 'email']
});

var store = Ext.create('Ext.data.Store', {
    model: 'User',
    proxy: {
        type: 'ajax',
        url : 'users.json',
        reader: {
            type: 'json'
        }
    }
});

The example above creates a 'User' model. Models are explained in the Model docs if you're not already familiar with them.

We created the simplest type of JSON Reader possible by simply telling our Store's Proxy that we want a JSON Reader. The Store automatically passes the configured model to the Store, so it is as if we passed this instead:

reader: {
    type : 'json',
    model: 'User'
}

The reader we set up is ready to read data from our server - at the moment it will accept a response like this:

[
    {
        "id": 1,
        "name": "Ed Spencer",
        "email": "ed@sencha.com"
    },
    {
        "id": 2,
        "name": "Abe Elias",
        "email": "abe@sencha.com"
    }
]

Reading other JSON formats

If you already have your JSON format defined and it doesn't look quite like what we have above, you can usually pass JsonReader a couple of configuration options to make it parse your format. For example, we can use the root configuration to parse data that comes back like this:

{
    "users": [
       {
           "id": 1,
           "name": "Ed Spencer",
           "email": "ed@sencha.com"
       },
       {
           "id": 2,
           "name": "Abe Elias",
           "email": "abe@sencha.com"
       }
    ]
}

To parse this we just pass in a root configuration that matches the 'users' above:

reader: {
    type: 'json',
    root: 'users'
}

Sometimes the JSON structure is even more complicated. Document databases like CouchDB often provide metadata around each record inside a nested structure like this:

{
    "total": 122,
    "offset": 0,
    "users": [
        {
            "id": "ed-spencer-1",
            "value": 1,
            "user": {
                "id": 1,
                "name": "Ed Spencer",
                "email": "ed@sencha.com"
            }
        }
    ]
}

In the case above the record data is nested an additional level inside the "users" array as each "user" item has additional metadata surrounding it ('id' and 'value' in this case). To parse data out of each "user" item in the JSON above we need to specify the record configuration like this:

reader: {
    type  : 'json',
    root  : 'users',
    record: 'user'
}

Response metadata

The server can return additional data in its response, such as the total number of records and the success status of the response. These are typically included in the JSON response like this:

{
    "total": 100,
    "success": true,
    "users": [
        {
            "id": 1,
            "name": "Ed Spencer",
            "email": "ed@sencha.com"
        }
    ]
}

If these properties are present in the JSON response they can be parsed out by the JsonReader and used by the Store that loaded it. We can set up the names of these properties by specifying a final pair of configuration options:

reader: {
    type : 'json',
    root : 'users',
    totalProperty  : 'total',
    successProperty: 'success'
}

These final options are not necessary to make the Reader work, but can be useful when the server needs to report an error or if it needs to indicate that there is a lot of data available of which only a subset is currently being returned.

Available since: 1.1.0

Defined By

Config options

Name of the property within a row object that contains a record identifier value. ...

Name of the property within a row object that contains a record identifier value. Defaults to The id of the model. If an idProperty is explicitly specified it will override that of the one specified on the model

Available since: 4.0.0

True to automatically parse models nested within other models in a response object. ...

True to automatically parse models nested within other models in a response object. See the Ext.data.reader.Reader intro docs for full explanation. Defaults to true.

Defaults to: true

Available since: 4.0.0

The name of the property which contains a response message. ...

The name of the property which contains a response message. This property is optional.

Available since: 3.4.0

Ext.data.reader.Json
view source
: String
The optional location within the JSON response that the record data itself can be found at. ...

The optional location within the JSON response that the record data itself can be found at. See the JsonReader intro docs for more details. This is not often needed.

Available since: 4.0.0

Ext.data.reader.Json
view source
: String
The name of the property which contains the Array of row objects. ...

The name of the property which contains the Array of row objects. For JSON reader it's dot-separated list of property names. For XML reader it's a CSS selector. For array reader it's not applicable.

By default the natural root of the data will be used. The root Json array, the root XML element, or the array.

The data packet value for this property should be an empty array to clear the data or show no data.

Defaults to: ''

Available since: 1.1.0

Overrides: Ext.data.reader.Reader.root

Name of the property from which to retrieve the success attribute. ...

Name of the property from which to retrieve the success attribute. Defaults to success. See Ext.data.proxy.Server.exception for additional information.

Defaults to: 'success'

Available since: 4.0.0

Name of the property from which to retrieve the total number of records in the dataset. ...

Name of the property from which to retrieve the total number of records in the dataset. This is only needed if the whole dataset is not passed in one go, but is being paged from the remote server. Defaults to total.

Defaults to: 'total'

Available since: 4.0.0

True to ensure that field names/mappings are treated as literals when reading values. ...

True to ensure that field names/mappings are treated as literals when reading values. Defalts to false. For example, by default, using the mapping "foo.bar.baz" will try and read a property foo from the root, then a property bar from foo, then a property baz from bar. Setting the simple accessors to true will read the property with the name "foo.bar.baz" direct from the root object.

Defaults to: false

Available since: 4.0.0

Defined By

Properties

Available since: 4.0.0

Ext.data.reader.Json
view source
: Objectprivate
Returns an accessor function for the given property string. ...

Returns an accessor function for the given property string. Gives support for properties such as the following: 'someProperty' 'some.property' 'some["property"]' This is used by buildExtractors to create optimized extractor functions when casting raw data into model instances.

Available since: 4.0.0

...

Defaults to: true

Available since: 4.0.0

Ext.data.reader.Json
view source
: Objectdeprecated
...

This property has been deprecated

will be removed in Ext JS 5.0. This is just a copy of this.rawData - use that instead

Available since: 1.1.0

The raw data object that was last passed to readRecords. ...

The raw data object that was last passed to readRecords. Stored for further processing if needed

Available since: 4.0.0

Get the reference to the current class from which this object was instantiated. ...

Get the reference to the current class from which this object was instantiated. Unlike statics, this.self is scope-dependent and it's meant to be used for dynamic inheritance. See statics for a detailed comparison

Ext.define('My.Cat', {
    statics: {
        speciesName: 'Cat' // My.Cat.speciesName = 'Cat'
    },

    constructor: function() {
        alert(this.self.speciesName); / dependent on 'this'

        return this;
    },

    clone: function() {
        return new this.self();
    }
});


Ext.define('My.SnowLeopard', {
    extend: 'My.Cat',
    statics: {
        speciesName: 'Snow Leopard'         // My.SnowLeopard.speciesName = 'Snow Leopard'
    }
});

var cat = new My.Cat();                     // alerts 'Cat'
var snowLeopard = new My.SnowLeopard();     // alerts 'Snow Leopard'

var clone = snowLeopard.clone();
alert(Ext.getClassName(clone));             // alerts 'My.SnowLeopard'

Available since: 4.0.0

Methods

Defined By

Instance Methods

Creates new Reader. ...

Creates new Reader.

Available since: 1.1.0

Parameters

  • config : Object (optional)

    Config object.

Returns

...

Available since: 4.0.6

Parameters

Returns

Ext.data.reader.Json
view source
( [force] )private
inherit docs This builds optimized functions for retrieving record data and meta data from an object. ...

inherit docs

This builds optimized functions for retrieving record data and meta data from an object. Subclasses may need to implement their own getRoot function.

Available since: 3.4.0

Parameters

  • force : Boolean (optional)

    True to automatically remove existing extractor functions first

    Defaults to: false

Overrides: Ext.data.reader.Reader.buildExtractors

...

Available since: 4.0.0

Call the original method that was previously overridden with override Ext.define('My.Cat', { constructor: functi...

Call the original method that was previously overridden with override

Ext.define('My.Cat', {
    constructor: function() {
        alert("I'm a cat!");

        return this;
    }
});

My.Cat.override({
    constructor: function() {
        alert("I'm going to be a cat!");

        var instance = this.callOverridden();

        alert("Meeeeoooowwww");

        return instance;
    }
});

var kitty = new My.Cat(); // alerts "I'm going to be a cat!"
                          // alerts "I'm a cat!"
                          // alerts "Meeeeoooowwww"

Available since: 4.0.0

Parameters

  • args : Array/Arguments

    The arguments, either an array or the arguments object

Returns

  • Object

    Returns the result after calling the overridden method

Call the parent's overridden method. ...

Call the parent's overridden method. For example:

Ext.define('My.own.A', {
    constructor: function(test) {
        alert(test);
    }
});

Ext.define('My.own.B', {
    extend: 'My.own.A',

    constructor: function(test) {
        alert(test);

        this.callParent([test + 1]);
    }
});

Ext.define('My.own.C', {
    extend: 'My.own.B',

    constructor: function() {
        alert("Going to call parent's overriden constructor...");

        this.callParent(arguments);
    }
});

var a = new My.own.A(1); // alerts '1'
var b = new My.own.B(1); // alerts '1', then alerts '2'
var c = new My.own.C(2); // alerts "Going to call parent's overriden constructor..."
                         // alerts '2', then alerts '3'

Available since: 4.0.0

Parameters

  • args : Array/Arguments

    The arguments, either an array or the arguments object from the current method, for example: this.callParent(arguments)

Returns

  • Object

    Returns the result from the superclass' method

Ext.data.reader.Json
view source
( root ) : Ext.data.Model[]private
We're just preparing the data for the superclass by pulling out the record objects we want. ...

We're just preparing the data for the superclass by pulling out the record objects we want. If a record was specified we have to pull those out of the larger JSON object, which is most of what this function is doing

Available since: 3.4.0

Parameters

  • root : Object

    The JSON root node

Returns

Overrides: Ext.data.reader.Reader.extractData

Given an object representing a single model instance's data, iterates over the model's fields and builds an object wi...

Given an object representing a single model instance's data, iterates over the model's fields and builds an object with the value for each field.

Available since: 3.4.0

Parameters

  • data : Object

    The data object to convert

Returns

  • Object

    Data object suitable for use with a model constructor

Used internally by readAssociated. ...

Used internally by readAssociated. Given a data object (which could be json, xml etc) for a specific record, this should return the relevant part of that data for the given association name. This is only really needed to support the XML Reader, which has to do a query to get the associated data object

Available since: 4.0.0

Parameters

  • data : Object

    The raw data object

  • associationName : String

    The name of the association to get data for (uses associationKey if present)

Returns

By default this function just returns what is passed to it. ...

By default this function just returns what is passed to it. It can be overridden in a subclass to return something else. See XmlReader for an example.

Available since: 4.0.0

Parameters

Returns

  • Object

    The normalized data object

...

Available since: 4.0.0

Get the idProperty to use for extracting data ...

Get the idProperty to use for extracting data

Available since: 4.0.0

Returns

Ext.data.reader.Json
view source
( response ) : Object
inherit docs Takes a raw response object (as passed to this.read) and returns the useful data segment of it. ...

inherit docs

Takes a raw response object (as passed to this.read) and returns the useful data segment of it. This must be implemented by each subclass

Available since: 4.0.0

Parameters

  • response : Object

    The responce object

Returns

  • Object

    The useful data from the response

Overrides: Ext.data.reader.Reader.getResponseData

This will usually need to be implemented in a subclass. ...

This will usually need to be implemented in a subclass. Given a generic data object (the type depends on the type of data we are reading), this function should return the object as configured by the Reader's 'root' meta data config. See XmlReader's getRoot implementation for an example. By default the same data object will simply be returned.

Available since: 3.4.0

Parameters

Returns

( config ) : Objectchainableprotected
Initialize configuration for this class. ...

Initialize configuration for this class. a typical example:

Ext.define('My.awesome.Class', {
    // The default config
    config: {
        name: 'Awesome',
        isAwesome: true
    },

    constructor: function(config) {
        this.initConfig(config);

        return this;
    }
});

var awesome = new My.awesome.Class({
    name: 'Super Awesome'
});

alert(awesome.getName()); // 'Super Awesome'

Available since: 4.0.0

Parameters

Returns

  • Object

    mixins The mixin prototypes as key - value pairs

( name, cls )private
Used internally by the mixins pre-processor ...

Used internally by the mixins pre-processor

Available since: 4.0.6

Parameters

Reconfigures the meta data tied to this Reader ...

Reconfigures the meta data tied to this Reader

Available since: 4.0.0

Parameters

( name, value )private
...

Available since: 4.0.6

Parameters

( name, fn )private
...

Available since: 4.0.0

Parameters

Reads the given response object. ...

Reads the given response object. This method normalizes the different types of response object that may be passed to it, before handing off the reading of records to the readRecords function.

Available since: 4.0.0

Parameters

  • response : Object

    The response object. This may be either an XMLHttpRequest object or a plain JS object

Returns

Loads a record's associations from the data object. ...

Loads a record's associations from the data object. This prepopulates hasMany and belongsTo associations on the record provided.

Available since: 4.0.0

Parameters

Returns

  • String

    Return value description

Ext.data.reader.Json
view source
( data ) : Ext.data.ResultSet
Reads a JSON object and returns a ResultSet. ...

Reads a JSON object and returns a ResultSet. Uses the internal getTotal and getSuccess extractors to retrieve meta data from the response, and extractData to turn the JSON data into model instances.

Available since: 1.1.0

Parameters

  • data : Object

    The raw JSON data

Returns

Overrides: Ext.data.reader.Reader.readRecords

( config ) : Ext.Basechainableprivate
...

Available since: 4.0.0

Parameters

Returns

( model, setOnProxy )private
Sets a new model for the reader. ...

Sets a new model for the reader.

Available since: 4.0.0

Parameters

  • model : Object

    The model to set.

  • setOnProxy : Boolean

    True to also set on the Proxy, if one is configured

Get the reference to the class from which this object was instantiated. ...

Get the reference to the class from which this object was instantiated. Note that unlike self, this.statics() is scope-independent and it always returns the class from which it was called, regardless of what this points to during run-time

Ext.define('My.Cat', {
    statics: {
        totalCreated: 0,
        speciesName: 'Cat' // My.Cat.speciesName = 'Cat'
    },

    constructor: function() {
        var statics = this.statics();

        alert(statics.speciesName);     // always equals to 'Cat' no matter what 'this' refers to
                                        // equivalent to: My.Cat.speciesName

        alert(this.self.speciesName);   // dependent on 'this'

        statics.totalCreated++;

        return this;
    },

    clone: function() {
        var cloned = new this.self;                      // dependent on 'this'

        cloned.groupName = this.statics().speciesName;   // equivalent to: My.Cat.speciesName

        return cloned;
    }
});


Ext.define('My.SnowLeopard', {
    extend: 'My.Cat',

    statics: {
        speciesName: 'Snow Leopard'     // My.SnowLeopard.speciesName = 'Snow Leopard'
    },

    constructor: function() {
        this.callParent();
    }
});

var cat = new My.Cat();                 // alerts 'Cat', then alerts 'Cat'

var snowLeopard = new My.SnowLeopard(); // alerts 'Cat', then alerts 'Snow Leopard'

var clone = snowLeopard.clone();
alert(Ext.getClassName(clone));         // alerts 'My.SnowLeopard'
alert(clone.groupName);                 // alerts 'Cat'

alert(My.Cat.totalCreated);             // alerts 3

Available since: 4.0.0

Returns

Defined By

Static Methods

( members ) : Ext.Basechainablestatic
Add / override static properties of this class. ...

Add / override static properties of this class.

Ext.define('My.cool.Class', {
    ...
});

My.cool.Class.addStatics({
    someProperty: 'someValue',      // My.cool.Class.someProperty = 'someValue'
    method1: function() { ... },    // My.cool.Class.method1 = function() { ... };
    method2: function() { ... }     // My.cool.Class.method2 = function() { ... };
});

Available since: 4.0.2

Parameters

Returns

( fromClass, members ) : Ext.Basechainablestatic
Borrow another class' members to the prototype of this class. ...

Borrow another class' members to the prototype of this class.

Ext.define('Bank', {
    money: '$$$',
    printMoney: function() {
        alert('$$$$$$$');
    }
});

Ext.define('Thief', {
    ...
});

Thief.borrow(Bank, ['money', 'printMoney']);

var steve = new Thief();

alert(steve.money); // alerts '$$$'
steve.printMoney(); // alerts '$$$$$$$'

Available since: 4.0.2

Parameters

  • fromClass : Ext.Base

    The class to borrow members from

  • members : String/String[]

    The names of the members to borrow

Returns

Create a new instance of this Class. ...

Create a new instance of this Class.

Ext.define('My.cool.Class', {
    ...
});

My.cool.Class.create({
    someConfig: true
});

All parameters are passed to the constructor of the class.

Available since: 4.0.2

Returns

( alias, origin )static
Create aliases for existing prototype methods. ...

Create aliases for existing prototype methods. Example:

Ext.define('My.cool.Class', {
    method1: function() { ... },
    method2: function() { ... }
});

var test = new My.cool.Class();

My.cool.Class.createAlias({
    method3: 'method1',
    method4: 'method2'
});

test.method3(); // test.method1()

My.cool.Class.createAlias('method5', 'method3');

test.method5(); // test.method3() -> test.method1()

Available since: 4.0.2

Parameters

Get the current class' name in string format. ...

Get the current class' name in string format.

Ext.define('My.cool.Class', {
    constructor: function() {
        alert(this.self.getName()); // alerts 'My.cool.Class'
    }
});

My.cool.Class.getName(); // 'My.cool.Class'

Available since: 4.0.4

Returns

Add methods / properties to the prototype of this class. ...

Add methods / properties to the prototype of this class.

Ext.define('My.awesome.Cat', {
    constructor: function() {
        ...
    }
});

 My.awesome.Cat.implement({
     meow: function() {
        alert('Meowww...');
     }
 });

 var kitty = new My.awesome.Cat;
 kitty.meow();

Available since: 4.0.2

Parameters

( members ) : Ext.Basechainablestatic
Override prototype members of this class. ...

Override prototype members of this class. Overridden methods can be invoked via callOverridden

Ext.define('My.Cat', {
    constructor: function() {
        alert("I'm a cat!");

        return this;
    }
});

My.Cat.override({
    constructor: function() {
        alert("I'm going to be a cat!");

        var instance = this.callOverridden();

        alert("Meeeeoooowwww");

        return instance;
    }
});

var kitty = new My.Cat(); // alerts "I'm going to be a cat!"
                          // alerts "I'm a cat!"
                          // alerts "Meeeeoooowwww"

Available since: 4.0.2

Parameters

Returns