Accessing nested objects in JSON feed - Sencha Touch - json

I'll begin with the usual disclaimer: new to Sencha Touch/working with JSON, floundering in the dark. Any help or prodding in the right direction is appreciated more than you know!
I'm trying to get my app to fetch data from a public Google Spreadsheet JSON feed. From what I've managed to figure out, my current model is based on JSON arrays, NOT nested objects. How do I access and return a nested object?
Ext.regModel('Count', {
fields: [{name:'$t'}]
});
this.list = new Ext.List({
itemTpl: new Ext.XTemplate('<div>{$t}</div>'),
loadingText: false,
store: new Ext.data.Store({
model: 'Count',
proxy: {
type: 'scripttag',
url : 'http://spreadsheets.google.com/feeds/cells/0AuYDRk91MX8-dHhkV29ZVkRGNjlvZjV4QVBIVmJubVE/odb/public/basic?range=A1&alt=json',
reader: {
type: 'json',
root: 'feed'
}
}
})
});
The JSON data (extra stuff removed, above link will show all of it if need be, contains an email address I'd rather not post and have indexed):
{
"feed":{
"entry":[{
"content":{
"type":"text",
"$t":"11"
}
}]
}
}
If I plop in another JSON feed that uses arrays I can work with it just fine, but just can't figure out what I need to do to access that integer in the object that corresponds to $t. If I put "entry" as the root instead of "feed," I get an error that reads, "Uncaught TypeError: Cannot read property 'length' of undefined."

The solution! Turns out Sencha didn't like the $ in my template variable.
Ext.regModel('Count', {
fields: [{name:'count', mapping:'content.$t'}]
});
this.list = new Ext.List({
itemTpl: new Ext.XTemplate('<div>{count}</div>'),
loadingText: false,
store: new Ext.data.Store({
model: 'Count',
proxy: {
type: 'scripttag',
url : 'http://spreadsheets.google.com/feeds/cells/0AuYDRk91MX8-dHhkV29ZVkRGNjlvZjV4QVBIVmJubVE/odb/public/basic?range=A1&alt=json',
reader: {
type: 'json',
root: 'feed.entry'
}
}
})
});

Related

Complicated nested json loops to store with extjs

I'm using a geojson extracted from naturalearthdata which looks like that :
All I want is to catch the NAME of each feature in order to display them in a grid (live search grid.. BTW is it efficient for 2000 names?)
But I can't access to all the name with root property. I tried to loop into all the features
Ext.define('myApp.store.Places', {
extend: 'Ext.data.Store',
alias: 'store.places',
requires : ['myApp.model.PlacesModel',
'myApp.view.main.MainModel'],
id: 'Places',
model: 'myApp.model.PlacesModel',
autoLoad: true,
proxy: {
type: 'ajax',
url : '/resources/data/coord.json',
reader: {
type: 'json',
transform: {
fn: function(data) {
for(var i = 0; i < data.features.length -1; i++){
names_places.push(data.features[i].properties.NAME);
}
debugger;
return names_places;
},
scope: this
}
}
}
});
But the debugger sent me that result which I don't understand :
Especially when the array looks good :
What is the good way to catch only the NAME? Does the return has to look to a json?
You can use the mapping attribute on the fields array in your model definition to map the correct attribute in the json to a field.
You set the rootProperty to features for the reader.
Then in your fields array something similar to this
fields: [
{ name: 'myCustomField', mapping: 'properties.NAME' }
]

How to make a store with jsonreader using metadata in Extjs 4?

Is it possible to create a store that will read json, and use fields specified in the metadata in the json as a model?
I want to say something like:
var store = new Ext.data.Store({
autoLoad: {
params: {
metaNeeded: true
}
},
reader: new Ext.data.JsonReader({fields:[]}),
proxy: new Ext.data.HttpProxy({
api: {
url: 'php/chart-data.php'
}
})
});
I've tried a number of combinations however I cannot seem to get it to work.
I currently get the error "Cannot call method 'indexOf' of undefined". I've had others including "object has no read method".
The json I am sending is:
{
metadata:{
root:"rows",
sortInfo:{
field:"date",
direction:"ASC"
},
fields:[ {
name:"date"
}, {
name:"flow"
},{
name:"limit"
}
],
idProperty:"date"
},
success:true,
rows: << snip >>
}
Is it possible to have the store's model configured by the data that it receives, so I could use the same store later with different fields (e.g. date, flow, limit and temperature)?
I have gotten it to work with the following:
var store = new Ext.data.Store({
proxy: {
type: 'ajax',
url: 'php/chart-data2.php',
reader: new Ext.data.JsonReader({
fields:[]
})
}
});
And the php that sends the json:
'{"metaData":{
"root":"rows",
"fields": [
{"name":"date",
"type":"number",
"convert": function(val, rec) {
return val*1000
} },
{"name":"flow"},
{"name":"limit"}
]
},
"totalCount":'.count($chart).',
"success":true,
"rows":' . json_encode($chart) . '
}'
This now allows the server to specify the data (that's getting displayed in a chart), and can add in series dynamically. I don't know if it is good, but it works. I am kind of disappointed in the lack of documentation about this.

loading data from json in sencha

I am creating an application where i have created a list and populated the data in the list using a data store.
data.js
Ext.regModel('Contact', {
fields: ['firstName', 'lastName', 'DOB', 'group']
});
iPolis.ListStore = new Ext.data.Store({
model: 'Contact',
sorters: 'lastName',
getGroupString : function(record) {
return record.get('group');
},
data: [
{ firstName: "Domino", lastName: "Derval" , DOB: "28May2008", group:"Personalize"},
]
});
This part of the code runs fine where i get the data and display it. Now what i require is a connection to the database and retriving the data in the data.js using a json file.
Any suggestions on how thats possible?
iPolis.ListStore = new Ext.data.Store({
model : 'Contact',
proxy : {
type : 'ajax',
url : 'js/person_list.json',
reader : {
type : 'json',
//root : 'results',
// totalCount : 'total'
}
},
autoLoad : true
});
used this for getting the data but it gives me an error sayin XMLHttprequest cannot load data in file.json
Go through the Ext.data.Proxy in Sencha API and also check the examples of store in API docs.
Just replace the url property of reader to the php file.
return proper JSON

How can i load data from a json file

i use extjs and load a json file with the store loader.
I want to load a json file. It will contain "totalRecords" and i want to put this in a var. For example var Records. This way i can display it at some positions of my app and use it for alerts.
thanks to your help i know have this:
total = Ext.create('Ext.data.Store', {
model: 'step1',
proxy: {
type: 'ajax',
url: 'testevents.json',
reader: {
type: 'json',
root: 'slaevents'
}
},
listeners: {
load: function() {
records = total.getRange()
test = records[0].get('event')
alert('1 =' +test)
}
},
autoLoad:true
});
alert('2 =' +test)
This will show alert with "1 =other". That is correct. And "2 =undifined". That is wrong. How can i use the test outside of this store?
Thanks
Realize that your store doesn't load instantly so it has nothing in it when you assign it to a variable immediately afterwards in the js. You need to listen for the store to load and then assign it, or assign it in a callback. For example, this works fine:
// get the countries
var countries = Ext.create('Ext.data.Store', {
fields: ['id','name'],
proxy: {
type: 'ajax',
url: '../getCountries',
reader: 'json'
},
listeners: {
load: function() {
records = countries.getRange()
alert(records[0].get('name'))
}
}
});
This alerts "Argentina".
records becomes an array of Ext.data.Model objects each of which have all the methods that Ext.data.Model has. This is covered here in the API.

How do I get an ExtJS JsonStore to put the JSON data directly into the request body?

I have a JsonStore configured like so:
var store = new Ext.data.JsonStore({
restful: true,
url: '/categories',
remoteSort: true,
idProperty: 'Id',
totalProperty: 'total',
root: 'results',
writer: new Ext.data.JsonWriter({
encode: false
}),
fields: [ 'Id', 'Name' ]
});
I grab some data from the server, then edit one of the records. When I tell the store to save, it sends this JSON back to the server:
{
"results":
{
"Name":"Trivial123",
"Id":2
}
}
The store is wrapping the JSON inside the results property (the root property configured on the store). However, the server expects this:
{
"Name":"Trivial123",
"Id":2
}
In other words, the serialized entity should be put directly in the response body, and not wrapped in a property. Does anyone know how I can configure the store to do this?
You need to override the data rendering function in the JsonWriter, like so:
var rootlessRenderFunction = function (params, baseParams, data) {
if (this.encode === true) {
Ext.apply(params, baseParams);
params = Ext.encode(data);
} else {
params.jsonData = data;
}
};
var myWriter = new Ext.data.JsonWriter({
encode: false,
writeAllFields: true
});
myWriter.render = rootlessRenderFunction;
var myStore = new Ext.data.JsonStore({
// ... various config values ...
writer: myWriter
});
This "rootlessRenderFunction" implementation is the same as the Ext JsonWriter's render code except it doesn't interpose a root in the request data.
This is a hack, of course.
I'm assuming you can't just not set the root value for the store for some reason? That's the way I normally do it.