Sencha Touch 2 read values from key AND value from nested JSON - json

I am trying to load some JSON, in which I store a lot of variables about some 100 anaesthetic drugs for pediatric patients.
The actual values get calculated before from patient's weight, age etc.:
Example:
var propofolInductionTitle = propofolName + ' ' + propofol0PercentConcentration + '- Induktion';
var propofol0InductionDosageMG = (Math.round(kg * 2 * 10) / 10) + ' - ' + (Math.round(kg * 5 * 10) / 10);
I then create my drug as a block of json consisting of the variables I need which are later to be replaced by the calculated values. I specifically try to avoid Strings in the JSON to allow for easier localization to english and french when all variables are defined in the math block.
var hypnotikaJSON = {
"thiopentalTitle": [
{"thiopentalBrandName": ""},
{"vialContentTitle": "thiopentalVialContent"},
{"solutionTitle": "thiopentalSolution"},
{"concentrationTitle": "thiopentalConcentration"},
{"dosageString": "thiopentalDosageString"},
{"atWeight": "thiopentalDosageMG"},
{"thiopentalAtConcentration": "thiopentalDosageML"}
],
"propofolInductionTitle": [
{"propofolInductionBrandName": ""},
{"propofolVialContentTitle": "propofolInductionVialContent"},
{"propofolSolutionTitle": "propofolSolution"},
{"propofolConcentrationTitle": "propofolInductionConcentration"},
{"propofolInductionDosageStringTitle": "propofolInductionDosageString"},
{"atWeight": "propofolInductionDosageMG"},
{"propofolAtInductionConcentration": "propofolInductionDosageML"}
],
"propofolSedationTitle": [
{"propofolSedationBrandName":""},
{"propofolVialContentTitle":"propofolSedationVialContent"},
{"propofolSolutionTitle":"propofolSolution"},
{"propofolConcentrationTitle":"propofolSedationConcentration"},
{"propofolSedationDosageStringTitle":"propofolSedationDosageString"},
{"atWeight":"propofolSedationDosageMG"},
{"propofolAtSedationConcentration":"propofolSedationDosageML"}
],
"laryngealMaskTitle": [
{"laryngealMaskSizeTitle":"laryngealMaskSize"},
{"laryngealMaskCuffSizeTitle":"laryngealMaskCuffSize"},
{"laryngealMaskBiggestETTTitle":"laryngealMaskBiggestETT"},
{"laryngealMaskBronchoscopeSizeTitle":"laryngealMaskBronchoscopeSize"}
]
};
My specific need is that the JSON reader has to give me the key AND value of each object as I need both to populate a template. The reason ist that the fields for the drugs are different in parts. Some have additional routes of administration so I have another key:value pair a different drug doesnt have. Some are given both as bolus and per drip, some arent. So no convenient json structure ist possible.
I found an answer by rdougan here that partly allowed me to do just that:
Model:
Ext.define('my.model.Drug', {
extend: 'Ext.data.Model',
config: {
fields: ['name', 'value']
}
});
Custom Json Reader:
Ext.define('Ext.data.reader.Custom', {
extend: 'Ext.data.reader.Json',
alias: 'reader.custom',
getRoot: function (data) {
if (this.rootAccessor) {
data = this.rootAccessor.call(this, data);
}
var values = [],
name;
for (name in data) {
values.push({
name: name,
value: data[name]
});
}
return values;
}
});
Store:
var store = Ext.create('Ext.data.Store', {
fields: ['name', 'value'],
data: hypnotikaJSON,
autoLoad: true,
proxy: {
type: 'memory',
reader: {
type: 'custom'
}
}
});
Panel:
this.viewport = new Ext.Panel({
fullscreen: true,
layout: 'fit',
items: [{
xtype: 'list',
itemTpl: '<p class="description">{name}</p><p class ="values">{value}</p>',
store: store
}]
});
Unfortunately I'm a physician and no programmer, and after a lot of reading I cant find out to apply this to a nested JSON. The custom reader seems to only go for the first level.
I could do it without a reader, without a store with just a lot of plan html around each entry, that has proven to be very very slow though so I would like to avoid it while updating from Sencha Touch 1.1. and better do it right this time.
Could you please point me to a way to parse this ugly data structure?
Thank you

I don't know much about extending JSON readers, so just guessing, but maybe you are supposed override the 'read' method? Then you can go over the JSON as you wish
Also, if you have control over the JSON you should consider changing it.
Usually, the keys in JSON should be the same throughout all items in the array.
keys are not data, they are metadata.
So, if you do have different properties between different drugs, then something like this might be a solution:
[{
name: 'Propofol 1%',
properties: [
{title: 'induction', value: '22-56g'},
{title: 'Sedation', value: '22'},
etc.
]},
{name: 'nextDrug'}
etc..

Related

Accessing an included object

I have the following JSON Object, which is the result of a loopback model (Classifications), with a relationship with another model (Labels).
My call to get the classifications is:
modClassification.findOne({
where: { id: classificationid },
include: 'labels' },
function( err, classification ){ ...
And this returns classification with something like
{ id: 'b01',
title: 'population',
country_id: 1,
labels:
[ { column_id: 'b1',
classification_id: 'b01',
classification_title: 'population',
dsporder: 1,
label: 'Total_Persons_Males',
country_id: 1,
id: 1 },
{ column_id: 'b2',
classification_id: 'b01',
classification_title: 'population',
dsporder: 2,
label: 'Total_Persons_Females',
country_id: 1,
id: 2 } ] }
which is what I would expect.
I now need to loop over the labels and access it's properties, but this is where I am stuck.
classification.labels[0] = undefined..
I have tried looping, each and whatever I can find online, but can't seem to get to each labels properties.
Can someone tell me what I am doing wrong/need to do?
Thanks
When you are including related models inside a findOne call, you need to JSONify the result before accessing the related records:
classification = classification.toJSON()
Then you should be able to access the included label items as you expect.
See https://docs.strongloop.com/display/public/LB/Include+filter, specifically the "Access included objects" section.
Note this does not work the same when you retrieve more than one result in an array. In that case you'll need to perform toJSON() on each item in the array.

Sequelize include (how to structure query)?

I have a query I'm trying to perform based on a one to many relationship.
As an example there is a model called Users and one called Projects.
Users hasMany Projects
Projects have many types which are stored in a type (enum) column. There are 4 different types that potentially a user may have that I want to load. The catch is I want to include the most recent project record (createdAt column) for all networks that potentially will be there. I have not found a way to structure the query for it to work as an include. I have however found a way to do a raw query which does what I want.
I am looking for a way without having to do a raw query. By doing the raw query I have to map the returned results to users I've returned from the other method, or I have to do a simple include and then trim off all the results that are not the most recent. The latter is fine, but I see this getting slower as a user will have many projects and it will keep growing steadily.
This allow serialize a json for anywhere action about a model. Read it, very well
sequelize-virtual-fields
// define models
var Person = sequelize.define('Person', { name: Sequelize.STRING });
var Task = sequelize.define('Task', {
name: Sequelize.STRING,
nameWithPerson: {
type: Sequelize.VIRTUAL,
get: function() { return this.name + ' (' + this.Person.name + ')' }
attributes: [ 'name' ],
include: [ { model: Person, attributes: [ 'name' ] } ],
order: [ ['name'], [ Person, 'name' ] ]
}
});
// define associations
Task.belongsTo(Person);
Person.hasMany(Task);
// activate virtual fields functionality
sequelize.initVirtualFields();

Is RethinkDB useful on partial updating json documents according rfc6902?

Please share your experience with partial updating of JSON document.At now I'm storing my JSON documents in MongoDB which looks like the following:
{
id: ObjectId(507f191e810c19729de860ea),
title: 'Sterling Archer',
comments: [
{text: 'Comment text', tags: ['tag1', 'tag2', 'tag3']},
{text: 'Comment test', tags: ['tag2', 'tag5']}
]
}
I need to frequently update my documents by using rfc6902 specification. Now, I do it not optimized way that looks the following (I use nodejs/express/mongoose and fast-json-patch module in this example):
var jsonpatch = require('fast-json-patch');
app.patch('/document/:id', function (req, res, next) {
var document_id = req.params.id;
// req.body.patch: { "op": "add", "path": "/comments/2", "value": {text: 'Comment test3', tags: ['tag4']}" }
var patches = req.body.patch;
// find document
Document.findById(document_id, function (err, document) {
// Applying patches
jsonpatch.apply(document, patches);
// Update whole document in MongoDB
Document.update({_id: document_id}, document, function (err) {
return res.status(200).send();
});
});
});
This is not optimize approach to patch documents due two queries in MongoDB and replacing whole document. So I'm looking for optimized approach and want to try RethinkDB for this task. Can you help me to inspect possibility of atomic document updating by using single query with RethinkDB? Or should I looks for another way of resolving my problem?
Please share your experience with partial updating of JSON document.
You just need one query in RethinkDB. Suppose you want to update the document whose id is 1 with the values {foo: 1, bar: 2}, and increment the field "count", you would do
r.table("data").get(1).update(function(doc) {
return doc.merge({foo: 1, bar:2, count: doc("count").add(1) })
})
While this update requires a unique query, the whole document will be updated.
If you have big documents, you can split them in multiple tables and perform joins later to retrieve the data.
You may be interested in reading this article about data modeling: http://www.rethinkdb.com/docs/data-modeling/

ExtJs - Creating a Grid from records in a database

I'm using ExtJS 4.2 and I have some records in a MySql database. My question is: How can I create a grid that displays the records in the database?
I tried using ResultSet in a servlet to retrieve the records from the database, but I'm not sure how to proceed from there.
How can i populate the fields in the grid with the records in my database?
I'm new to ExtJS and I'm finding it difficult to come up with a solution for this. Does this have something to do with the store field? If so, how do i go about achieving the above said requirement?
You need to create store, bind to the grid and then load data from server. And sure you need backend for this ExtJS4 do not provide any tools for working with databases
For example( taken from sencha docs ):
Ext.onReady(function(){
Ext.define('Book',{
extend: 'Ext.data.Model',
proxy: {
type: 'ajax',
reader: 'xml'
},
fields: [
// set up the fields mapping into the xml doc
// The first needs mapping, the others are very basic
{name: 'Author', mapping: '#author.name'},
'Title', 'Manufacturer', 'ProductGroup'
]
});
// create the Data Store
var store = Ext.create('Ext.data.Store', {
model: 'Book',
autoLoad: true,
proxy: {
// load using HTTP
type: 'ajax',
url: 'sheldon.xml',
// the return will be XML, so lets set up a reader
reader: {
type: 'xml',
// records will have an "Item" tag
record: 'Item',
idProperty: 'ASIN',
totalRecords: '#total'
}
}
});
// create the grid
Ext.create('Ext.grid.Panel', {
store: store,
columns: [
{text: "Author", flex: 1, dataIndex: 'Author'},
{text: "Title", width: 180, dataIndex: 'Title'},
{text: "Manufacturer", width: 115, dataIndex: 'Manufacturer'},
{text: "Product Group", width: 100, dataIndex: 'ProductGroup'}
],
renderTo:'example-grid',
width: 540,
height: 200
});
});
The main idea is - models are for defining structure of the record and validation(read about it here), stores - for storing and fetching(by parsing response from server or local defined data) records that match model structure(Basic store) and finally grid handles some events(like "load" or "refresh") and updating rows based on grids column defenition(docs)

Sending grouped json data with ajax

I'm using extJS version 4.0 to generate a entry form. On that form there is a save button that sends all the fielddata to php via ajax. As transfer protocol for the data itself I'm using json.
As I need to make a dynamical (general) routine for processing this data (as that one form won't be the only form in that project) I would need that json data grouped somehow. One of the requirements I have is that I need the "fieldnames" to be as they are (as I use the fieldnames I get transmitted to me to access the approopriate coloumns in the database in the automatic save routine).
My question here is is there any way to somehow group the data that is transmitted via json (thus that extJS groups it).
As a simplified example:
On the entryform I'm saving data for 2 tables (1. Person 2. bankaccount) which have the following fields shown on the form:
-firstname
-lastname
for person
and
-account number
-bank number
for bankaccount
(the stores are accordingly)
Is there a way with extJS to group this data acordingly, thus generate something like this?
{"person":[{"firstname": "Mark", "lastname":"Smith"}],"bankaccount":[{"account number":123112,"bank number":1A22A1}]}
Currently I'm getting something like this:
{"firstname": "Mark", "lastname":"Smith","account number":123112,"bank number":1A22A1}
Both person and bankaccount are in their separate stores.
Tnx.
Well, you've two stores: one for 'person' and one for 'bankaccount'.
Ext.define ('Person', {
extend: 'Ext.data.Model' ,
fields: ['firstname', 'lastname']
});
Ext.define ('BankAccount', {
extend: 'Ext.data.Model' ,
fields: ['accountnumber', 'banknumber']
});
var personStore = Ext.create ('Ext.data.Store', {
model: 'Person' ,
data: [
{firstname: 'foo', lastname: 'bar'} ,
{firstname: 'zoo', lastname: 'zar'} ,
{firstname: 'too', lastname: 'tar'} ,
{firstname: 'goo', lastname: 'gar'} ,
{firstname: 'moo', lastname: 'mar'}
]
});
var bankAccountStore = Ext.create ('Ext.data.Store', {
model: 'BankAccount' ,
data: [
{accountnumber: 10000, banknumber: 10000} ,
{accountnumber: 20000, banknumber: 20000} ,
{accountnumber: 30000, banknumber: 30000} ,
{accountnumber: 40000, banknumber: 40000} ,
{accountnumber: 50000, banknumber: 50000}
]
});
Then, you want to dump these stores as JSON. No problem!
Make a container (jsonData) and then fill it up with your stores:
var jsonData = {
person: [] ,
bankaccount: []
};
personStore.each (function (person) {
jsonData.person.push (person.data);
});
bankAccountStore.each (function (bank) {
jsonData.bankaccount.push (bank.data);
});
console.log (Ext.JSON.encode (jsonData));
And this is the output on the console:
{"person":[{"firstname":"foo","lastname":"bar"},{"firstname":"zoo","lastname":"zar"},{"firstname":"too","lastname":"tar"},{"firstname":"goo","lastname":"gar"},{"firstname":"moo","lastname":"mar"}],"bankaccount":[{"accountnumber":10000,"banknumber":10000},{"accountnumber":20000,"banknumber":20000},{"accountnumber":30000,"banknumber":30000},{"accountnumber":40000,"banknumber":40000},{"accountnumber":50000,"banknumber":50000}]}
Is that what you've requested?
Here's the fiddle