Datatables process json response multiple objects - json

Im using Datatables Jquery plugin to do a bit of work, but i havent been able to understand how to process the Json response im getting from the server .
I get this response:
"aaData":[
[
{
"idTreatment":23,
"treatment":"Hospitalización",
"directions":"Directions",
"active":"1"
},
{
"idCIE10":1,
"cieCode":"A00",
"diagnostic":"COLERA",
"description":null,
"lastUsed":1386649580000,
"active":1
}
],
[
{
"idTreatment":27,
"treatment":"Antibiótico",
"directions":null,
"active":"1"
},
{
"idCIE10":1,
"cieCode":"A00",
"diagnostic":"COLERA",
"description":null,
"lastUsed":1386649580000,
"active":1
}
],
[
{
"idTreatment":33,
"treatment":"Hidratación Oral",
"directions":"Directions",
"active":"1"
},
{
"idCIE10":1,
"cieCode":"A00",
"diagnostic":"COLERA",
"description":null,
"lastUsed":1386649580000,
"active":1
}
]
]
}
I have been trying to use mData or mRender, but im not familiarized with datatables yet, so i would be really grateful if someone could thell me how can in print this in a table on html
thanks in advance
this javascript fucntion is the one im using to initialize the table, im trying to use aoColumns based on examples but im not sure if this is the best option; also based on example im using mData, to show just 2 columns for test, as you can see im trying to acces the "array" or the json response using the objects field names, but when the page is rendering theres a warning saying that it cant find the field.
function initializeTreatmentsTable(id){
treatmentsTable = $('#treatmentsTable').dataTable( {
"bSort":false,
"sAjaxSource":"./diagnosticTreatment",
"fnServerParams": function ( aoData ) { aoData.push( {name:"diagnosticId",value:id} ); },
"aoColumns": [
{ "mData": "idTreatment" },
{ "mData": "treatment" }
]
});

Well after looking several times over the API in the official website datatables.net i came to the conclusion that i had to test out.
If my problem isn't clear i will explain it again.
i have a table, and that table's data is obtained by a ajax request and a json response, the json response is a array of object but the objects themselves are composed of at least 2 objects ( {[[object1][object2]],[[object1][object2]]} ) so accessing them with mData was impossible at least for me, and the solution was so simple that i wonder i never tried, i just had to use mRender and a function.
function initializeTreatmentsTable(id){
treatmentsTable = $('#treatmentsTable').dataTable( {
"bSort":false,
"sAjaxSource":"./diagnosticTreatment",
"fnServerParams": function ( aoData ) { aoData.push( {name:"diagnosticId",value:id} ); },
"aoColumns": [
{ "bVisible": false,
"mRender": function(data,type,full){
return data.idTreatment;}
},
{ "mRender": function(data,type,full){
return full[0].treatment;
} }
]
});
The function above its the one im using to initialise the table for the first time, i got the problem that i just wanted 2 field from the first object and none from the second one, but i dont now how to do it, so i used the "full" parameter that contains the whole json response, and accesed it.
This might not be the best answer but it did the work for me, so i hope that if someone know how to improved it , feel free to do it, or so just comment , and i also hope this can help someone else.

Related

Best Schema for a Data List in JSON for RestFul API to use in Angular

I've been wondering for some days what kind of scheme would be more appropriate to use a data list in json in a web application.
I'm developing a REST Web Application, and im using Angular for front end, i should order, filter and print these data list also in xml ...
For you what scheme is better and why?
1) {
"datas": [
{ "first":"","second":""},
{ "first":"","second":""},
{ "first":"","second":""}
]
}
2) {
"datas": [{
"data": { "first":"","second":""},
"data": { "first":"","second":""},
"data": { "first":"","second":""}
}]
}
3) [
{ "first":"","second":""},
{ "first":"","second":""},
{ "first":"","second":""}
]
Thanks so much.
The first and third notations are quite similar because the third notation is included in your first.
So the question is "Should I return my datas as an array or should I return an object with a property that contain the array ?
It will depend on either you want to have more information alongside your datas or not.
For exemple, if your API might return an error, you will want to manage it from the front end.
In case of error, the JSON will looks like this :
{
"datas": null,
"error": "An error occured because of some reasons..."
}
At the opposite, if everything goes well and your API actually return the results, it will looks like this :
{
"datas": [
{ "first":"","second":""},
{ "first":"","second":""},
{ "first":"","second":""}
],
"error": null
}
Then your front end can use the error property to manage errors sent from the API.
var result = getDatas(); // Load datas from the API
if(result.error){
// Handle the error, display a message to the user, ...
} else {
doSomething(result.datas); // Use your datas
}
If you don't need to have extra properties like error then you can stick with the third schema.
The second notation is invalid. The datas array will contain only one object which will have one property named data. In this case data is a property that is defined multiple times so the object in the array will contain only the last occurence:
var result = {
"datas": [{
"data": { "first":"a","second":"b"},
"data": { "first":"c","second":"d"},
"data": { "first":"e","second":"f"}
}]
}
console.log("Content of result.datas[0].data : ")
console.log(result.datas[0].data)
Obviously the first option would be easy to use. Once you will access datas it'll give you an array. Any operation (filter, sort, print) on that array will be easy in comparison to anything else. Everywhere you just need to pass datas not datas.data.

Is there a way of getting a cleaner JSON out of Couchdb?

I am wondering if there is a way to get a cleaner JSON with just the docs out of Couchdb instead of getting it under "rows" and then "doc"
This is the default output
{
"total_rows":1,
"offset":0,
"rows":[
{
"id":"7d9fd5824f9029186c1eec1bda005e75",
"key":"7d9fd5824f9029186c1eec1bda005e75",
"value":{
"rev":"1-f99879f67cfd27685f92c884c236a0fd"
},
"doc":{
"_id":"7d9fd5824f9029186c1eec1bda005e75",
"_rev":"1-f99879f67cfd27685f92c884c236a0fd",
"title":"Hello World",
"messeges":"This is the first messege. Helloo there"
}
}
]
}
This is the desired output:
{
"_id":"7d9fd5824f9029186c1eec1bda005e75",
"_rev":"1-f99879f67cfd27685f92c884c236a0fd",
"title":"Hello World",
"messeges":"This is the first messege. Helloo there"
}
Thanks
It would be useful to see your code. I suspect this is the output of the alldocs api? If you know the ID of the document you want you can use the get api which returns the JSON you want. Otherwise you must loop through the "rows" ie
for (x in results.rows) {...}
and then use x.doc to get your JSON.
Thanks all for the help.
I figured out a way doing it in Node js by using a map function attached to there query
in the nano page they listed it as
alice.list().then((body) => {
body.rows.forEach((doc) => {
console.log(doc);
});
});
instead I used it like this
alice.list().then((body) => {
var result = body.rows.map( (x) => {
return x.doc
});
console.log(result);
});
which works for me.
Still new till couchdb and databases in general.

Dynamic JSON structure

I am trying to make a JSON-key dynamic with the following data and function:
var jsonData = [ ];
addProcess("Text1", "Text2", jsonData)
function addProcessingPurpose(title, domain, arr) {
arr.push({
"First": title,
domain : {
"subitem": {
"Subsubitem": "text"
}
}
});
}
I get the desired output expect I don't seem to manage setting the keys dynamically from the function parameter. E.g. now it prints "domain" instead of "Text2" which is my desired output. How can this be solved please?
Sorry for the stupid question, solved it myself didn't saw I forgot the [ ] around the key.. Thank you anyway, maybe it can help someone else..

Zapier identifying JSON data as string

My question is how can I pull the values for events.payload.media.name?
I am posting to a raw zapier webhook from another app. If I check it using requestb.in it comes through as "Content-Type: application/json". The output is also validating as JSON.
{
"hook":{
"uuid":"1asdfasd5-asdf-4f52-bd31-c7a544897808"
},
"events":[
{
"uuid":"0asdfasdfasdf0",
"type":"viewing_session.turnstile.converted",
"payload":{
"visitor":{
"id":"28b606b_7853753-3868-4f07-9543-70da084452cc-7442322af-407bdc31d8fc-2739"
},
"viewing_session":{
"id":"154284_b40c5358-1faf-40e9-a44e-60aa641a11cd-fd3c69d8d-302471c603f4-8245"
},
"name":null,
"media":{
"url":"https://things.wistia.com/medias/asdfasdf",
"thumbnail":{
"url":"http://embed.wistia.com/deliveries/asdfasdfasdfasdfasdfasdfasd.jpg?image_crop_resized=200x120"
},
"name":"this is what I want!",
"id":"asdfasdfasdf",
"duration":52.872
},
"last_name":null,
"foreign_data":{
},
"first_name":null,
"email":"email#email.com"
},
"metadata":{
"account_id":"asdfasdfasdf"
},
"generated_at":"2017-05-02T07:31:08Z"
}
]
}
However, when I check the typeof data in the output it is telling me that it is a string (see my code to check below). This prevents me from pulling the info out of it using:
return {stuff: typeof inputData.thing.events.payload.media.name};
I'm a huge noob, am I missing something fundamental here?
screenshot to check typeof data
events is an array, so you would access it like this:
inputData.thing.events[0].payload.media.name
is there a way to have the whole payload without creating a new App in Zapier? inputData didn't work

Sencha Touch - Accessing Associated-Model Store JSON via Nested Looping

I've been lurking on Stack Overflow for quite some time now, and have found quite a number of very helpful answers. Many thanks to the community! I hope to be able to contribute my own helpful answers before too long.
In the meantime, I have another issue I can't figure out. I am using Sencha Touch to create a Web-based phone app and I'm having trouble using a nested loop to iterate through some JSON. I can grab the first level of data, but not the items nested within that first level. There is a somewhat related ExtJS thread, but I decided to create my own since ExtJS and Touch diverge in subtle yet important ways. Anyway, here is some code to show where I am:
JSON (truncated - the JSON is PHP/MYSQL-generated, and there are currently actually three sub levels with "title", all of which I can access. It's the sub level "items" through which I can't iterate):
{
"lists": [
{
"title": "Groceries",
"id": "1",
"items": [
{
"text": "contact solution - COUPON",
"listId": "1",
"id": "4",
"leaf": "true"
},
{
"text": "Falafel (bulk)",
"listId": "1",
"id": "161",
"leaf": "true"
},
{
"text": "brita filters",
"listId": "1",
"id": "166",
"leaf": "true"
}
]
}
]
}
Store:
var storeItms = new Ext.data.Store({
model: 'Lists',
proxy: {
type: 'ajax',
method: 'post',
url : LIST_SRC,
extraParams: {action: 'gtLstItms'},
reader: {
type: 'json',
root: 'lists'
}
}
});
Working Loop:
storeItms.on('load', function(){
var lstArr = new Array();
storeItms.each(function(i) {
var title = i.data.title;
lstArr.push(i.data.title);
});
console.log(lstArr);
});
Non-working Nested Loop:
storeItms.on('load', function(){
var lstArr = new Array();
storeItms.each(function(i) {
var title = i.data.title;
var id = i.data.id;
title.items.each(function(l) {
lstArr.push(l.data.text);
});
});
console.log(lstArr);
});
The non-working nested loop gives me the error "Cannot call method 'each' of undefined", in reference to 'title.items.each...'
I suspect this is because I've not set title to be a key to set up a key:value pair, so it just sees a list of strings...but I'm kind of at a loss.
I should mention that the store is populated via two Models that have been associated with one another. I know that the Store can access everything because I am able to do nested iterating via an XTemplate.
Any help will be much appreciated and hopefully returned to the community in kind before too long!'
-Eric
Eric, why the loop?
If your models are associated in the same way that the JSON is nested, then you should just be able to set autoLoad:true on the store, sit back and enjoy.
Anyway, on the assumption that you are needing these arrays for some other unrelated reason, the problem is that you are trying .each on
i.data.title.items
Surely you should be iterating through
i.data.items
Also, if the object is a model, you can use .get() instead of the data object:
var title = i.get('title);
Using new sencha touch 2 framework, you can create associations within the models exactly the same way how your json is returned.
Check Sencha Touch 2 Model Document which tells you the various config options on Model.
You may refer to this example of ST2 Nested List .
Hope this helps.
"title" is not a enumerable object, its a string. To iterate a string you'll need to split it to convert it into an array.
Also, instead of using Ext.each try a simple for (var x in obj) {} or for (var xc in obj.prop) {} If that works then the ext.each method should work as well but if ext cannot iterate the object it will just quietly fail.