Access the certain key of json response [AngularJS] - javascript

Here is my angular code
$scope.StartCPU = function () {
//Initialize the Timer to run every 1000 milliseconds i.e. one second.
$scope.GetCPUData = $interval(function(){
$http.get('http://localhost:3034/api/test/metrics').
success(function(data, status, headers, config) {
$scope.Details = data;
});}, 1000);
};
Html code as follows
<div ng-controller="HttpGetController">
<button ng-click="StartCPU()">Get All Data</button>
<h1>CPU data</h1>
<pre>{{Details | json}}</pre>
</div>
I am getting the response as below
{
"data": [
{
"_id": "57ee5641931b429431085fc4",
"system": 0.06249,
"process": 0.0091652,
"timestamp": "2016-09-30T12:10:40.780Z",
"__v": 0,
"createdAt": "2016-09-30T12:10:41.927Z"
}
]
}
Now I want to access the value of the keys "system" and "process". How can I do it?

data.data[0].system
and data.data[0].process
Explanation: Here your data is an Object with property data.
//complete thing is your response data
{
"data": [ // data.data <--array
{ // data.data[0] <--first object of the array
"_id": "57ee5641931b429431085fc4",
"system": 0.06249,// data.data[0].system <--its property
"process": 0.0091652,
"timestamp": "2016-09-30T12:10:40.780Z",
"__v": 0,
"createdAt": "2016-09-30T12:10:41.927Z"
}
]
}

In your data object that you get from the call, you have the propertydata which is an array
You should then call the first element of the array
data.data[0]
Which will return you
{
"_id": "57ee5641931b429431085fc4",
"system": 0.06249,
"process": 0.0091652,
"timestamp": "2016-09-30T12:10:40.780Z",
"__v": 0,
"createdAt": "2016-09-30T12:10:41.927Z"
}
Then you call the elements that you need
data.data[0].system
data.data[0].process

It means it returns an array, may you can use something like this:
<table class="table datatable">
<thead>
<tr>
<th>system</th>
<th>process</th>
</tr>
</thead>
<tbody ng-repeat="detail in Details">
<tr>
<td>{{detail.system}}</td>
<td>{{detail.process}}</td>
</tr>
</tbody>
</table>

Related

Sending Json data as an object into DataTables

I have been trying to use DataTables. But after my Ajax request i get a Json object which i cannot pass into dataTables.
The Json object i receive is the following
{"data": [{"attributes": {"purchasedate": "04/01/2017", "medication": "meds", "cost": 100.0, "expirydate": "04/03/2017", "quantity": 100.0}, "type": "medical_inventory"}, {"attributes": {"purchasedate": "04/01/2017", "medication": "Extra Meds", "cost": 100.0, "expirydate": "04/02/2017", "quantity": 100.0}, "type": "medical_inventory"}, {"attributes": {"purchasedate": "04/01/2017", "medication": "Extra Super Meds", "cost": 267.0, "expirydate": "04/11/2017", "quantity": 250.0}, "type": "medical_inventory"}], "links": {"self": "/medical_inventory/"}}
Following is my HTML code
<table id="myTable" class="display" cellspacing="0" width="90%">
<thead>
<tr>
<th>Medication</th>
<th>Medication Quantity</th>
<th>Mediaction Cost</th>
<th>Purchase Date</th>
<th>Expiry Date</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Medication</th>
<th>Medication Quantity</th>
<th>Mediaction Cost</th>
<th>Purchase Date</th>
<th>Expiry Date</th>
</tr>
</tfoot>
</table>
The Ajax request i do is the following
$(document).ready(function () {
$.ajax({
url : '/api/medical_inventory/',
type : 'GET',
dataType : 'json',
success : function(data) {
assignToEventsColumns(data);
}
});
function assignToEventsColumns(data) {
var table = $('#myTable').dataTable({
"bAutoWidth" : false,
"aaData" : data,
"columns" : [ {
"data" : "medication"
}, {
"data" : "quantity"
}, {
"data" : "cost"
}, {
"data" : "purchasedate"
}, {
"data" : "expirydate"
} ]
})
}
});
This is the output i am currently getting
You were very nearly there:
function assignToEventsColumns(data) {
var table = $('#myTable').dataTable({
"bAutoWidth": false,
"aaData": data.data,
"columns": [{
"data": "attributes.medication"
}, {
"data": "attributes.quantity"
}, {
"data": "attributes.cost"
}, {
"data": "attributes.purchasedate"
}, {
"data": "attributes.expirydate"
}]
})
}
All you were missing was the structure of your JSON, you needed to add attributes. as well as your data.data :-D.Working JSFiddle here.
Try mapping the data to remove the attributes property of each object
success : function(data) {
data.data = data.data.map(function(item){
return item.attributes;
});
assignToEventsColumns(data);
}

Unable to bind json data to a table using angularjs

Hi i am Trying to Bind JSON object Data to a table.my issue is i am able to bind entire json object {{metric}} but failed to load each atttribute of json object i.e.,{{metric.EmpId}}.
finally from my observation i found when the converted json object is directly asigned to
$scope.Employees="Employee": [
{"EmpId": "4",
"Name": "Chris",
"Sex": "Male",
"Phone": [
{
"_Type": "Home",
"__text": "564-555-0122"
},
{
"_Type": "Work",
"__text": "442-555-0154"
}
],
"Address": {
"Street": "124 Kutbay",
"City": "Montara",
"State": "CA",
"Zip": "94037",
"Country": "USA"
}
}
]
}
the output is working as i expected but when i assign the direct result
i.e,$scope.Employees=response;it is not working what might be the issue
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="xml2json.js"></script>
<script>
var app = angular.module('httpApp', []);
app.controller('httpController', function ($scope, $http) {
$http.get("File1.xml",
{
transformResponse: function (cnv) {
var x2js = new X2JS();
var aftCnv = x2js.xml_str2json(cnv);
return aftCnv;
}
})
.success(function (response) {
console.log(response);
$scope.Employees = response;
console.log($scope.Employees);
});
});
</script>
<div>
<div ng-app="httpApp" ng-controller="httpController">
<div ng-repeat="metric in Employees">
{{ metric}}
<br />
<br />
<table>
<tr ng-repeat="metric in Employees">
{{metric}}
<td ng-repeat="cell in metric">{{cell}}</td>
<td>{{cell.EmpId}}</td>
<td>{{metric.Name}}</td>
</tr>
</table>
</div>
</div>
Assuming your json has the following format:
$scope.Employees = {
"Employee": [
{
"EmpId": 1,
"Name": "Sam"
},
{
"EmpId": 2,
"Name": "Lucy"
}
]
};
You probably would want to do this:
<div ng-repeat="employeeList in Employees">
<table>
<tr ng-repeat="employee in employeeList">
<td>{{employee.EmpId}}</td>
<td>{{employee.Name}}</td>
</tr>
</table>
</div>

order of the facebook page graph comments with angularjs

I put comments of a facebook post in a angularjs loop in http://plnkr.co/edit/bMykiulfzN8tscqfySFA?p=preview
data is from https://graph.facebook.com/618857251494402_804740479572744?access_token=343397335795533|zjYg_5xoTUepxDrTXLYYQR6VDrc
<table class="table table-striped">
<thead>
<tr>
<th>comment</th>
<th>date</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="resource in employees | limitTo:2 | orderBy:'created_time':true">
<td>{{ resource.message }}</td>
<td>{{ resource.created_time }}</td>
</tr>
</tbody>
</table>
Problem is the order : i want the two last comments in the time, but when i put limitTo:2, it's show the two firsts comments ... So, how to get the two lasts comments with limitTo ?
In angular filters work as a chain when they are combined, meaning subsequent filter will get the result of previous filter(in the same expression) to work with the data set. In your case you are limiting the initial set of data to 2 records and then ordering the 2 records by creationDate. So you should just place the limitTo:2 after orderBy filter.
Try:-
<tr ng-repeat="resource in employees | orderBy:'created_time':true | limitTo:2">
You do not need to add another filter or reinvent the wheel when we already have one provided along with the angular which is well tested and more efficient (possibly).
Also as a side note, if you are always displaying a static number of latest items (i.e the items or the limit does not change dynamically without the interaction of some trigger), better move the filter to the controller logic (initialization or on a specific action method like a click event etc) and bind with the filtered data. DOM Filters (or filters on the view) are expensive and they add upon to the digest cycle.
Demo
angular.module('app', []).controller('ctrl', function($scope){
$scope.employees = getData().comments.data;
function getData() {
return {
"id": "618857251494402_804740479572744",
"from": {
"category": "Community",
"name": "Sexe, Clashs, Batman, Becs Bunsen & Soucoupes Volantes : LE MONDE DU RAT",
"id": "618857251494402"
},
"message": "POST",
"privacy": {
"value": ""
},
"type": "status",
"status_type": "mobile_status_update",
"created_time": "2014-12-18T00:17:36+0000",
"updated_time": "2014-12-18T19:23:14+0000",
"is_hidden": true,
"comments": {
"data": [
{
"id": "804740479572744_804740636239395",
"from": {
"category": "Community",
"name": "Sexe, Clashs, Batman, Becs Bunsen & Soucoupes Volantes : LE MONDE DU RAT",
"id": "618857251494402"
},
"message": "test1 (first in the time)",
"can_remove": false,
"created_time": "2014-12-18T00:18:25+0000",
"like_count": 0,
"user_likes": false
},
{
"id": "804740479572744_804779462902179",
"from": {
"category": "Reference website",
"name": "Adopte Un Rat - adopteunrat.com",
"id": "809567735752704"
},
"message": "test",
"can_remove": false,
"created_time": "2014-12-18T01:27:27+0000",
"like_count": 0,
"user_likes": false
},
{
"id": "804740479572744_804967526216706",
"from": {
"category": "Community",
"name": "Sexe, Clashs, Batman, Becs Bunsen & Soucoupes Volantes : LE MONDE DU RAT",
"id": "618857251494402"
},
"message": "test3",
"can_remove": false,
"created_time": "2014-12-18T13:31:22+0000",
"like_count": 0,
"user_likes": false
},
{
"id": "804740479572744_805082169538575",
"from": {
"category": "Community",
"name": "Sexe, Clashs, Batman, Becs Bunsen & Soucoupes Volantes : LE MONDE DU RAT",
"id": "618857251494402"
},
"message": "test4 (last in the time)",
"can_remove": false,
"created_time": "2014-12-18T19:23:14+0000",
"like_count": 0,
"user_likes": false
}
],
"paging": {
"cursors": {
"after": "WTI5dGJXVnVkRjlqZFhKemIzSTZPREExTURneU1UWTVOVE00TlRjMU9qRTBNVGc1TXpBMU9UUTZMVEU9",
"before": "WTI5dGJXVnVkRjlqZFhKemIzSTZPREEwTnpRd05qTTJNak01TXprMU9qRTBNVGc0TmpFNU1EWTZMVEU9"
}
}
}
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<table class="table table-striped">
<thead>
<tr>
<th>comment</th>
<th>date</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="resource in employees | orderBy:'created_time':true | limitTo:2">
<td>{{ resource.message }}</td>
<td>{{ resource.created_time }}</td>
</tr>
</tbody>
</table>
</div>

Table not being filled from Ajax Call using Datatables plug-in for jQuery

The ajax request is returning the following data
[{"ID":40,"Date":"\/Date(1407999600000)\/"},{"ID":39,"Date":"\/Date(1409036400000)\/"}
The HTML is:
<table id="bookings-table" class="display">
<thead>
<tr>
<th>ID</th>
<th>Date</th>
</tr>
</thead>
<tfoot>
<tr>
<th>ID</th>
<th>Date</th>
</tr>
</tfoot>
</table>
And the javascript is
$(document).ready(function () {
$('#bookings-table').dataTable({
"ajaxSource": "/manager/Booking/GetBookings",
"columns": [
{ "data": "ID" },
{ "data": "Date" }
]
});
});
Any idea why the table is not being filled
Just looking at their docs, I believe your json has to be formatted as so.
{
"data": [
{
"ID": 40,
"Date": "\/Date(1407999600000)\/"
},
{
"ID": 39,
"Date": "\/Date(1409036400000)\/"
}
]
}
Javascript error
$('#bookings-table').dataTable({
"ajax": {
"url": "/manager/Booking/GetBookings",
"dataSrc": ""
},
Sorted it all columns now bind

populate datatable from a local json file

I am trying to populate my datatable using a JSON file (jsontext.json) I tried almost all the resources but can't work this one out. I have tried all the stackoverflow resources. This question is different than the one that are posted.
If I could just get the JSON file into the my jsonObject then the rest I can figure out.
The Json file is stored in my c:\path\jsontext.json
Here is the json file
[
{
"Identifier": "1",
"Label": "pratik",
"Categories": "Standard",
"UpdatedBy": "lno",
"UpdatedAt": "01-02-2013"
},
{
"Identifier": "2",
"Label": "2013",
"Categories": "Standard",
"UpdatedBy": "lno",
"UpdatedAt": "01-02-2013"
}
]
I tried the following js code to get the file into jsonObject
var myObject;
$.ready(function(){
myObject={};
$.getJSON('http://localhost:8080/jsontext.json', function(data){
/* here I have tried using both the paths the c:\path\jsontext.json and the one above */
myObject=data;
});
});
Once i have it into the JsonObject I can use the following code to populate the datatable
$(document).ready(function(){
$('#example').dataTable
( {
"sScrollY": "200px",
"bPaginate": false,
"bScrollCollapse": true,
aaData:myObject,
"aoColumns":
[
{ "mData": "Identifier" },
{ "mData": "Label" },
{ "mData": "Categories" },
{ "mData": "UpdatedBy" },
{ "mData": "UpdatedAt" },
{ "sClass": "getimage"},
{ "sClass": "editimage"},
{ "sClass": "deleteimage"}
]
});
});
Here is my html body in my jsp page
<body id="dt_example">
<div id="container">
<table cellpadding="0" cellspacing="0" border="0" class="display" id="example">
<thead>
<ul>
<li> Add Code Edit</li>
<li> Import</li>
<li> Export</li>
</ul>
<tr>
<th>Identifier</th>
<th>Label</th>
<th>Categories</th>
<th>UpdatedBy</th>
<th>UpdatedAt</th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1 Data 1</td>
<td>Row 1 Data 2</td>
<td>Row 1 Data 3</td>
<td>Row 1 Data 4</td>
<td>Row 1 Data 5</td>
<td class="getimage"></td>
<td class="editimage"></td>
<td class="deleteimage"></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
can Anyone tell me where I am going wrong.
Actually, if you see the server response in developer tools you can find the data that is received. As far as I have worked with the dataTables, the json file must contain a "key" for the whole data, otherwise it wont have any reference.
Try modifying your json as follows:
{
"mydata":[
{
"Identifier": "1",
"Label": "pratik",
"Categories": "Standard",
"UpdatedBy": "lno",
"UpdatedAt": "01-02-2013"
},
{
"Identifier": "2",
"Label": "2013",
"Categories": "Standard",
"UpdatedBy": "lno",
"UpdatedAt": "01-02-2013"
}
]
}
if you want to use the json object other than "aaData", you can use "sAjaxDataProp" of the datatable to specify the respective object.
Looks like the problem could be that your ajax is loading and setting the myObject variable but it is done after Datatables initialized so it does not get the updated myObject variable after your request has finished. You could do something like this to fix that:
var myObject;
$.ready(function(){
myObject={};
$.getJSON('http://localhost:8080/jsontext.json', function(data){
/* here I have tried using both the paths the c:\path\jsontext.json and the one above */
myObject=data;
$('#example').dataTable().fnAddData(myObject);
});
});
Thanks for the replys every one I got the answer I tried out thanks though.
var someData=JSON.parse(document.getElementById("populate-holdingBin").innerHTML);
oTables=$('#someReport').dataTable
({
"bJQueryUI":true,
"bScrollCollapse":true,
aaData:someData,
"aoColumns":
[ ...etc etc.............................. ]
});

Categories