Angular parse response from database - angularjs

I have response from database:
{"status":"success","message":"Data selected from database","data":[{"id":1171,"sku":0,"word_one":"one word","description":"","word_two":"two word","mrp":0,"lang_one":"en","image":"","lang_two":"en","status":"Active","category":"[{\"text\":\"someone\"},{\"text\":\"sometwo\"}]","UserID":188},
...
{"id":1170,"sku":0,"word_one":"something","description":"","word_two":"some two","mrp":0,"lang_one":"en","image":"","lang_two":"en","status":"Active","category":"[{\"text\":\"ever\"},{\"text\":\"never\"}]","UserID":188}]}
Before I make post: angular.toJson($scope.category);
How I can show category something like this
{{category}} = someone, sometwo ?
Because actually I have string :
[{"text":"someone"},{"text":"sometwo"}]
[{"text":"ever"},{"text":"never"}]
...

You can use the below parsing to achieve what you want. Suppose json is the variable received from database.
var json = {"status":"success","message":"Data selected from database","data":[{"id":1171,"sku":0,"word_one":"one word","description":"","word_two":"two word","mrp":0,"lang_one":"en","image":"","lang_two":"en","status":"Active","category":"[{\"text\":\"someone\"},{\"text\":\"sometwo\"}]","UserID":188}]};
var data = json.data[0].category;
var jsonArray = JSON.parse(data);
var category = "";
jsonArray.map(function(obj, i ) {
if(i != 0) {
category += ",";
}
category += obj.text;
});
console.log(category)
At the end , You attach category to $scope.category.

This work:
var parsed = JSON.parse($scope.c.category);
var arr = [];
for(var x in parsed){
arr.push(parsed[x]);
}
$scope.c.category = arr;

Related

How to extract information from nested arrays with multiple objects?? (AdminReport.Activities.list)

Could anyone point me in the correct direction?
I searched plenty... I had no luck with mapping... or "find" nor extracting the data I need.
My code:
function checkMeetCode(meetCode, index, searchDate) {
var ss=SpreadsheetApp.getActive().getSheetByName('AsistenciaMeet');
var colB = ss.getRange("D3:D").getValues();
var filasLlenasLengthB = colB.filter(String).length; //
var userKey = 'all';
var applicationName = 'meet';
var emailAddress = colB[index];
Logger.log("Index / Alumno: "+index+" / " + emailAddress);
var optionalArgs = {
event_name: "call_ended",
endTime: searchDate,
startTime: fechaRestada(searchDate),
filters: "identifier==" + emailAddress + ",meeting_code==" + meetCode
};
var response = AdminReports.Activities.list(userKey, applicationName, optionalArgs)
Logger.log("RESPONSE: "+response);
var actividad = response.items;
if (actividad == null) {
// do nothing
}
else {
**// HERE IS WHERE I AM TRYING TO FIND / EXTRACT INFORMATION FROM "response"
// READ BELOW PLEASE.**
}
}
NEED HELP WITH:
I want to FIND/EXTRACT the intValue of "duration_seconds":
The results from:
Logger.log("RESPONSE: "+response);
RESPONSE: {"kind":"admin#reports#activities","etag":"\"JDMC8884sebSctZ17CIssbQ/IhilrSKVziEhoZ7URUpQ-NrztHY\"","items":[{"events":[{"parameters":[{"name":"video_send_seconds","intValue":"1829"},{"name":"screencast_recv_packet_loss_mean","intValue":"0"},{"name":"identifier_type","value":"email_address"},{"name":"video_send_packet_loss_max","intValue":"0"},{"name":"endpoint_id","value":"meet_android_4154513448557872"},{"name":"video_recv_long_side_median_pixels","intValue":"320"},{"name":"calendar_event_id","value":"44jr4vu3qo75q6bvkknq_20200421T213000Z"},{"name":"video_send_fps_mean","intValue":"29"},{"name":"video_recv_short_side_median_pixels","intValue":"180"},{"name":"network_estimated_download_kbps_mean","intValue":"351"},{"name":"duration_seconds","intValue":"1830"},{"name":"video_send_bitrate_kbps_mean","intValue":"762"},{"name":"network_recv_jitter_msec_max","intValue":"130"},{"name":"ip_address","value":"186.59.21.55"},{"name":"audio_send_seconds","intValue":"1829"},{"name":"screencast_recv_packet_loss_max","intValue":"0"},{"name":"video_recv_seconds","intValue":"1818"},{"name":"network_rtt_msec_mean","intValue":"36"},{"name":"video_send_long_side_median_pixels","intValue":"640"},{"name":"screencast_recv_seconds","intValue":"1829"},{"name":"product_type","value":"meet"},{"name":"video_recv_packet_loss_max","intValue":"0"},{"name":"is_external","boolValue":false}],"name":"call_ended","type":"call"}] ...
OK, after roughly 8 hours... I was able to make it work.
var insideParameters = response["items"][0]["events"][0]["parameters"];
Logger.log(insideParameters.length);
for (var i = 30; i<insideParameters.length;i++){ // its always located above i = 30...
if(insideParameters[i].name === "duration_seconds"){
var duration = insideParameters[i].intValue;
Logger.log(duration);
}
}

App script/maker and Big Query

I having an google app (app maker) where I script the following code:
function runQuery() {
var projectId = 'projekte-123425512';
var request = {
query: 'SELECT title FROM [bigquery-public-data:samples.wikipedia] where title contains "olimpic" LIMIT 100'
};
var queryResults = BigQuery.Jobs.query(request, projectId);
var jobId = queryResults.jobReference.jobId;
var names = queryResults.schema.fields.map(function(field){ return field.name; });
return queryResults.rows.map(function(row) {
var obj = {};
for( var i = 0, len = names.length; i < len; ++i ) {
obj[names[i]] = row.f[i].v;
}
return obj;
});
}
So I basically try to get some data out of Big Query and store it in an array. Later I want it as a calculated model and a data source in my app:
I already tried it and get result in my logger:
It works! But only in app script debugger, then I want to test the whole app I get the following error:
The function queryRecords must return an array of records, but the array contained an element that was not a record. Error: The function queryRecords must return an array of records, but the array contained an element that was not a record.
EDIT
I updated my code
function runQuery() {
var projectId = 'nifty-stage-155512';
var request = {
query: 'SELECT title FROM [bigquery-public-data:samples.wikipedia] where title contains "olimpic" LIMIT 100'
};
var queryResults = BigQuery.Jobs.query(request, projectId);
var jobId = queryResults.jobReference.jobId;
var names = queryResults.schema.fields.map(function(field){ return field.name; });
//var records = [];
return queryResults.rows.map(function(row) {
var record = app.models.Test.newRecord();
for (var i = 0, len = names.length; i < len; ++i) {
// Calculated model should contain correspondent fields
// all non-defined fields will be ignored
record[names[i]] = (row.f[i].v);
}
return record;
});
}
It now works without error but I still get no data into my grid:
Is there something I'am missing in the configuration of the grid or the datasource??
App Maker doesn't allow to return arbitrary objects through its datasources. All results should be strongly typed:
...
return queryResults.rows.map(function(row) {
var record = app.models.CalcModelName.newRecord();
for (var i = 0, len = names.length; i < len; ++i) {
// Calculated model should contain correspondent fields
// all non-defined fields will be ignored
record[names[i]] = row.f[i].v;
}
return record;
});
Here are some samples for reference
https://developers.google.com/appmaker/samples/calculated-model/
https://developers.google.com/appmaker/samples/jdbc/

Adding Markers to Google map from json Array

This is my poor code
function loaddata() {
var url = "http://localhost/Geocording/api.php";
$.getJSON(url, function (data) {
var json = data
for (var i = 0, length = json.length; i < length; i++) {
var val = json[i],
var latLng = new google.maps.LatLng(val.lat, val.lng);
console.log(latLng)
}
});
}
Im trying to get details from my own api using json array.
but its not working.
{"location":[{"name":"Home 1","lat":"6.824367","lng":"80.034523","type":"1"},{"name":"Grid Tower 1","lat":"6.82371292","lng":"80.03451942","type":"1"},{"name":"Power Station A","lat":"6.82291793","lng":"80.03417451","type":"1"}],"success":1}
This is json response from my api.php
Try to make things clear first then apply it. First read JSON clearly then go on to apply it in your code. This is the working code.
function loaddata() {
var url = "http://localhost/Geocording/api.php";
$.getJSON(url, function (data) {
var json = data['location'];
for (var i = 0, length = json.length; i < length; i++) {
var val = json[i];
var latLng = new google.maps.LatLng(val['lat'], val['lng']);
console.log(latLng)
}
});
}
Hope this may help you!

How to split and parse particular value of json array using Angularjs?

How can i split and parse particular json data using angularjs.
My json is
[{"id":"1", "stud":" name=Alex, roll_no=12 | class=12,sec=1" , "tech":"Sam"},
{"id":"2", "stud":" name=john, roll_no=13 | class=12,sec=2" , "tech":"Sandy"},
{"id":"3", "stud":" name=Cate, roll_no=14 | class=12,sec=1" , "tech":"Sandy"},
]
I want to parse this json formated data like if ID =1 .
Name= Alex.
Roll No=12.
Class=12.
Section=1.
Teacher=Sam.
Iterate through the collection with reduce.
On every Object in the collection parse the stud attribute with Regular Expressions. Create the new string and add it to the new collection.
// Pseudocode
collection.reduce((memo, item) => {
const values = item.stud.match(" name=Alex, roll_no=12 | class=12,sec=1".match(/^ name=(\w*), roll_no=(\d{2}).../))
// Add it to memo in a format you like
return memo
})
I wrote you some functions...
function getRowFromJson(json, id){
for(var i=0; i<json.length; i++)
if('undefined' == json[i].id) continue;
else if(json[i].id==id) return json[i];
return false;
}
function parseStudFromRow(row){
var stud = {};
var chunks = row.stud.split("|");
for(var i=0; i<chunks.length; i++){
var morechunks = chunks[i].split(",");
for(var n=0; n<morechunks.length; n++){
var chunkage = morechunks[n].split("=");
stud[chunkage[0].trim()] = chunkage[1].trim();
}
}
return stud;
}
You use it like this..
var row = getRowFromJson(json, 1);
var stud = parseStudFromRow(row);
console.log(stud);
Check out the example.. https://jsfiddle.net/o0v6nyzu/2/

Why $http response data are not shown in angular js?

I make a example of directive in angular js .I am using this directive
https://github.com/ONE-LOGIC/ngFlowchart
when I take static data ..it show the output please check my plunker
http://plnkr.co/edit/d2hAhkFG0oN3HPBRS9UU?p=preview
but when I use $http request and make same json object .it not display the chart see my plunker using $http request .I have same data object as in static
http://plnkr.co/edit/Vts6GdT0NNudZr2SJgVY?p=preview
$http.get('data.json').success(function(data) {
console.log(data)
var arr = data
var model={};
var new_array = []
for (var i = 0; i < arr.length; i++) {
var obj = {};
obj.name = arr[i].name;
obj.id = arr[i].id;
obj.x = arr[i].x;
obj.y = arr[i].y;
obj.color = '#000';
obj.borderColor = '#000';
var p = {};
p.type = 'flowchartConstants.bottomConnectorType';
p.id = arr[i].con_id
obj.connectors = [];
obj.connectors.push(p);
new_array.push(obj);
}
console.log('new array')
console.log(new_array)
model.nodes=new_array;
var edge = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i].children.length > 0) {
for (var j = 0; j < arr[i].children.length; j++) {
var obj = {};
obj.source = arr[i].con_id;
obj.destination = arr[i].children[j].con_id;
edge.push(obj);
}
}
}
model.edges=edge;
console.log(edge)
console.log("model")
console.log(JSON.stringify(model))
$scope.flowchartselected = [];
var modelservice = Modelfactory(model, $scope.flowchartselected);
$scope.model = model;
$scope.modelservice = modelservice;
})
any update ?
Working Example
It is now working.
The issue was when we load the directive first time it has no parameter value to it. So, when the chart directive try to initialize your chart with no parameter it gets an error. So, it will not work anymore.
How solve the issue?
Just give a dummy parameter upon the page load. I have given the dummy model as,
$scope.model = model;
$scope.modelservice = modelservice;
So, first your chart will display a chart based on the dummy values. After that it populates chart with the data from the server ($http.get())

Resources