How to create hierarchical JSON from API in AngularJs and MySQL - mysql

I am trying to figure out how to output a structured JSON from a query to my API. I have the following 2 tables (MySQL):
**TABLE1:**
uid
name
pptw
**TABLE2**
id
table1_uid
assignment
start_time
end_time
date
comments
And this is the JSON output I am looking for:
$scope.table1 = {
"toplevel":
[
{
"uid": 1,
"name": "john",
"pptw": "ATWF",
"child":
{
"id": 1,
"table1_uid": 1,
"assignment": null,
"start_time": "14:53:00",
"end_time": "15:00:00",
"date": null,
"comments": null
}
},
{
"uid": 22,
"name": "carol",
"pptw": "DWFF",
"child":
{
"id": 2,
"table1_uid": 22,
"assignment": null,
"start_time": "11:00:00",
"end_time": "14:00:00",
"date": null,
"comments": "Completed"
}
}
]
}
I have a promise as follow:
var request = $http({
method: 'post',
url: '.../api/v1/ppp',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
params: {
//record_uid: record_uid,
}
})
.success(function (data, status, headers, config) {
deferred.resolve(data);
})
.error(function (data, status) {
deferred.reject();
});
return deferred.promise;
And on the database, I have the following query:
SELECT tb1.uid
tb1.name
tb1.pptw,
tb2.id,
tb2.table1_uid,
tb2.assignment,
tb2.start_time,
tb2.end_time,
tb2.date,
tb2.comments
FROM
table1 tb1, table2 tb2
WHERE
tb1.uid = tb2.table1_uid
I would appreciate any ideas on how to achieve this, thanks a lot.

This is the solution to my questions, I managed to figure out how to do it. I hope it helps someone else trying to do the same thing as I did.
Here is how to create the hierarchical JSON:
var results_tree_header = [];
var results_tree = [];
if (result.rows.length > 0) {
for (var i = 0; i < result.rows.length; i++) {
results_tree.push({
"uid": result.rows.item(i).uid,
"name": result.rows.item(i).name,
"pptw": result.rows.item(i).pptw,
"child":
{
"id": result.rows.item(i).id,
"table1_uid": result.rows.item(i).table1_uid,
"assignment": result.rows.item(i).assignment,
"start_time": result.rows.item(i).start_time,
"end_time": result.rows.item(i).end_time,
"date": result.rows.item(i).date,
"comments": result.rows.item(i).comments
}
});
results_tree_header = { toplevel: results_tree };
}
}

Related

How to retrive data from multiple tables. Using node js and mysql?

I have two tables which are give in at this fiddle.
http://sqlfiddle.com/#!9/d37102
I want to retrieve data from the table currently I am doing this way
mysqlConnection.query("SELECT* FROM wallet WHERE user_id = ? ORDER by date",authData.id,(err,rows,fields)=>{
if(!err){
res.json({
message :"Statement",
rechargeDetails : rows,
transactionDetail://// TODO: Transaction details
});
}
else console.log(err);
});
That is correctly retrieving the JSON data in at this format over here
{
"message": "Statement",
"rechargeDetails": [
{
"id": 17,
"amount": 50,
"type": "CREDIT",
"pg_id": "xxxxq123",
"comments": null,
"intrument_type": "REFUND",
"user_id": 1,
"date": "2020-04-17T18:30:00.000Z"
},
{
"id": 18,
"amount": 50,
"type": "CREDIT",
"pg_id": "xxxxq123",
"comments": null,
"intrument_type": "REFUND",
"user_id": 1,
"date": "2020-04-17T18:30:00.000Z"
}
]
}
I want to get transaction table data also like this
{
"message": "Statement",
"rechargeDetails": [
{
"id": 17,
"amount": 50,
"type": "CREDIT",
"pg_id": "xxxxq123",
"comments": null,
"intrument_type": "REFUND",
"user_id": 1,
"date": "2020-04-17T18:30:00.000Z"
},
{
"id": 18,
"amount": 50,
"type": "CREDIT",
"pg_id": "xxxxq123",
"comments": null,
"intrument_type": "REFUND",
"user_id": 1,
"date": "2020-04-17T18:30:00.000Z"
}
"transactionDetails": [
{
"id": 17,
"amount": 50,
"tax": "CREDIT",
"discount": "xxxxq123",
"adjustment": null,
"refrence_id": "REFUND",
"payment_ref_id": 1,
xxxxxx
xxxxxxxxxx
}
],
}
How could i do that? Is there a way to do this?
mysqlConnection.query("SELECT * FROM wallet WHERE user_id = ? ORDER by date",authData.id,(err,rows,fields)=>{
if(!err){
mysqlConnection.query("SELECT * FROM transaction WHERE user_id = ? ORDER by date",authData.id,(errTarn,rowsTarn,fieldsTarn)=>{
if(!errTarn){
res.json({
message :"Statement",
rechargeDetails : rows,
transactionDetail: rowsTarn
});
}
});
}
else console.log(err);
});
OR YOU CAN USE MULTIPLE QUERY
enable it for your connection
var connection = mysql.createConnection({multipleStatements: true});
Now the code will be
connection.query('SELECT * FROM wallet WHERE user_id = ? ORDER by date; SELECT * FROM transaction WHERE user_id = ? ORDER by date', [authData.id, authData.id], function(err, results) {
if (err) throw err;
if(!err){
res.json({
message :"Statement",
rechargeDetails : results[0],
transactionDetail: results[1]
});
}
});
I have zero knowledge with NODE but I think something like this should work properly
mysqlConnection.query("SELECT* FROM wallet WHERE user_id = ? ORDER by date",authData.id,(err,rows,fields)=>{
if(!err){
res.json({
message :"Statement",
rechargeDetails : rows,
transactionDetail: mysqlConnection.query("__SELECT_TRANSACTIONS_QUERY__",authData.PARAMETER_NEEDED,(err,rows,fields)=>{
if(!err){
// return your rows
}
});
});
} else {
console.log(err);
}
});

Ecobee: Response returning only partial results

Using Google Apps script to attempt to talk to my thermostat using the Ecobee API. In the below code, the value of json is "{ "status": { "code": 0, "message": "" } }". For the correct, full response, see the results of curl later in the question.
For some reason response is only getting the final element (status) out of the three results that are returned by the server (page, thermostatList, and status).
What am I missing?
Google Apps Script is as follows:
function getSettings() {
var response = fetchSettings();
var json = response.getContentText();
var data = JSON.parse(json);
// response, json, and data only show `status` result
}
function fetchSettings() {
try {
var headers = {
'Authorization': 'Bearer AUTH_TOKEN'
};
var payload = {
'selection' : {
'selectionType':'registered',
'selectionMatch': '',
'includeRuntime': 'true'
}
};
var options = {
'method': 'get',
'headers': headers,
'contentType': 'text/json',
'payload': JSON.stringify(payload);
};
var URL = 'https://api.ecobee.com/1/thermostat?format=json'
return UrlFetchApp.fetch(URL,options);
} catch(e) {
return e;
}
}
Using curl as follows:
curl -s -H 'Content-Type: text/json' -H 'Authorization: Bearer AUTH_TOKEN' 'https://api.ecobee.com/1/thermostat?format=json&body=\{"selection":\{"selectionType":"registered","selectionMatch":"",includeRuntime":true\}\}'
I get full results.
{
"page": {
"page": 1,
"totalPages": 1,
"pageSize": 2,
"total": 2
},
"thermostatList": [
{
"identifier": "12345",
"name": "Downstairs",
"thermostatRev": "160528163253",
"isRegistered": true,
"modelNumber": "athenaSmart",
"brand": "ecobee",
"features": "",
"lastModified": "2016-05-28 16:32:53",
"thermostatTime": "2016-05-28 11:57:00",
"utcTime": "2016-05-28 16:57:00",
"runtime": {
"runtimeRev": "160528165546",
"connected": true,
"firstConnected": "2015-08-20 21:57:53",
"connectDateTime": "2016-05-26 08:56:18",
"disconnectDateTime": "2016-05-26 00:00:00",
"lastModified": "2016-05-28 16:55:46",
"lastStatusModified": "2016-05-28 16:55:46",
"runtimeDate": "2016-05-28",
"runtimeInterval": 200,
"actualTemperature": 703,
"actualHumidity": 49,
"desiredHeat": 670,
"desiredCool": 810,
"desiredHumidity": 44,
"desiredDehumidity": 56,
"desiredFanMode": "on"
}
},
{
"identifier": "310166836750",
"name": "Upstairs",
"thermostatRev": "160528162656",
"isRegistered": true,
"modelNumber": "athenaSmart",
"brand": "ecobee",
"features": "",
"lastModified": "2016-05-28 16:26:56",
"thermostatTime": "2016-05-28 11:57:00",
"utcTime": "2016-05-28 16:57:00",
"runtime": {
"runtimeRev": "160528165523",
"connected": true,
"firstConnected": "2015-09-28 13:33:41",
"connectDateTime": "2016-05-26 08:55:35",
"disconnectDateTime": "2016-05-26 00:00:00",
"lastModified": "2016-05-28 16:55:23",
"lastStatusModified": "2016-05-28 16:55:23",
"runtimeDate": "2016-05-28",
"runtimeInterval": 201,
"actualTemperature": 712,
"actualHumidity": 49,
"desiredHeat": 600,
"desiredCool": 840,
"desiredHumidity": 36,
"desiredDehumidity": 60,
"desiredFanMode": "auto"
}
}
],
"status": {
"code": 0,
"message": ""
}
}
I think the problem is that UrlFetchApp doesn't support sending payload using the get method as a query string. I assume this is correct design for UrlFetchApp and poor design on the part of the Ecobee API. I made a kluge workaround by sending the JSON in a query string myself as follows.
var URL = 'https://api.ecobee.com/1/thermostat?body='+encodeURIComponent(JSON.stringify(payload));

How to display data from a json file in angularjs?

I have a json something like this
{
"count": 67,
"0": {
"id": "2443",
"name": "Art Gallery",
"category": {
"id": "2246",
"name": "Gifts & Memories"
},
"deckLocation": [
{
"id": "2443",
"deck": {
"deckNo": "7",
"deckName": "Promenade "
},
}
]
},
"1": {
"id": "7198",
"name": "Captain's Circle Desk",
"category": {
"id": "352",
"name": "Other Services"
},
"deckLocation": [
{
"id": "7198",
"deck": {
"deckNo": "7",
"deckName": "Promenade "
},
},
{
"id": "7198",
"deck": {
"deckNo": "7",
"deckName": "Promenade "
},
}
]
}
}
I want to display all names which is inside the "0", "1" array. I can able to list a specific name but not all. The fist name will display which I written in the following code. But I need to display all 0, 1, 2, 3 etc names dynamically.
data[0].name
Please help me.
Thank you.
use ng-repeat function to do so.
<div ng-repeat = "names in data">
<P>{{names.name}}</P>
</div>
Let us say you have a service like this:-
var todoApp = angular.module("todoApp",[]);
todoApp.factory('dbService', ['$q','$http',function ($q , $http) {
var service ={};
service.getUrl = function (urlToGet) {
var svc=this;
var deferred = $q.defer();
var responsePromise = $http.get(urlToGet);
responsePromise.success(function (data, status, headers, config) {
deferred.resolve(data); });
responsePromise.error(function (data, status, headers, config) {
deferred.reject({ error: "Ajax Failed", errorInfo: data });});
return (deferred.promise);
}
return service;
}]);
And you want to load a file named '/js/udata.json'. Here is how in you controller you can load this file:-
todoApp.controller("ToDoCtrl", ['$scope','$timeout','dbService',function($scope, $timeout, dbService)
{
$scope.todo={};
$timeout(function(){
dbService.getUrl('/js/udata.json').then(function(resp){
$scope.todo=resp;
});},1);
};
Hope this helps!
You have data[0].name right?
then why don't you loop through that to get all the name elements in those arrays.
like...
for(i=1;i<data.length;i++)
{
console.log(data[i].name);
}

NodeJS remove outer json key, keep inner?

I have the following JSON:
{
"result": "success",
"json": {
"'1'-'V17511500523287'": [{
"hits": 1,
"sid": 1,
}]
}
}
I would like to turn it into:
{
"result": "success",
"json": [{
"hits": 1,
"sid": 1,
}],
"length": 1
}
Meaning id like to remove "'1'-'V17511500523287'" but keep the inner content.
Is this somehow possible?
You can use Object.keys(...) to get the keys in your result and then use it to get the inner content like you want.
Here is some code to achieve that. Put it in a function if you plan to do that elsewhere.
var response = {
"result": "success",
"json": {
"'1'-'V17511500523287'": [{
"hits": 1,
"sid": 1,
}]
}
};
var response_keys = Object.keys(response.json);
response.length = response_keys.length;
if (response_keys.length == 1) {
response.json = response.json[response_keys[0]];
} else {
// you can drop that if you don't want to handle more than one key,
// or throw/return an error instead
var _tmp = [];
response_keys.forEach(function(key) {
_tmp.push(response.json[key]);
});
response.json = _tmp;
_tmp = undefined;
}
console.log(JSON.stringify(response, null, 2));
Output:
{
"result": "success",
"json": [
{
"hits": 1,
"sid": 1
}
],
"length": 1
}

How to control keys to show in Json Object

I am using following NodeJs code to get the JsonObject:
cdb.getMulti(['emp1','emp2'],null, function(err, rows) {
var resp = {};
for(index in rows){
resp[index] = rows[index];
}
res.send(resp);
});
Getting output :
{
"emp1": {
"cas": {
"0": 637861888,
"1": 967242753
},
"flags": 0,
"value": {
"eid": "10",
"ename": "ameen",
"gender": "male",
"designation": "manager",
"country": "Singapur",
"reportee": "Suresh",
"salary": 50000,
"picture": "ameen.jpg"
}
},
"emp2": {
"cas": {
"0": 721747968,
"1": 430939000
},
"flags": 0,
"value": {
"eid": "2",
"ename": "shanmugapriya",
"gender": "female",
"designation": "programmer",
"country": "England",
"reportee": "shruti",
"salary": 14250,
"picture": "priya.jpg"
}
}
}
What I want to do is, I want to display only value key. Can anybody help me how to do this.
Thanks in advance.
Do you mean you want to display only value and key? If so the code below will put only value into the result
cdb.getMulti(['emp1','emp2'],null, function(err, rows) {
var resp = {};
for(index in rows){
resp[index] = rows[index].value;
}
res.send(resp);
});
The result response will be
{
"emp1":{
"eid":"10",
"ename":"ameen",
"gender":"male",
"designation":"manager",
"country":"Singapur",
"reportee":"Suresh",
"salary":50000,
"picture":"ameen.jpg"
},
"emp2":{
"eid":"2",
"ename":"shanmugapriya",
"gender":"female",
"designation":"programmer",
"country":"England",
"reportee":"shruti",
"salary":14250,
"picture":"priya.jpg"
}
}
UPDATE: Your question was really ambiguous. I think you would need to use Couchbase Views here. Docs http://docs.couchbase.com/couchbase-sdk-node-1.2/#querying-a-view. Assuming that you will build the view _design/employees/_view/all with the following map function:
function(doc, meta) {
emit(meta.id, doc);
}
Your node.js code will look like this
var view = bucket.view('employees', 'all');
view.query(function(err, results) {
res.send(results);
});