How to display data from a json file in angularjs? - json

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);
}

Related

Meteor JSON Method and Call in template

I am trying to call a Meteor method with a parsed json doc to use in my template. None of my calls work and I then need advise on how to display (maybe I should save this part for another post - but any suggestions would be helpful) in template with helpers. I am new to meteor and javascript.
Json doc
{
"sports-content": {
"sport-event": [{
"event-metadata": {
"league": "NCAA Basketball",
"event-type": "0",
"league-details": "NCAAB",
"event-date-time": "12/18/2015 07:00 PM",
"eventNum": "3000460",
"status": "",
"off-the-board": "False"
},
"team": [{
"team-metadata": {
"alignment": "Home",
"nss": "526",
"openNum": "526",
"name": {
"full": "Clemson"
}
},
"wagering-stats": {
"wagering-straight-spread": {
"bookmaker-name": "BetOnline",
"active": "true",
"line": "1.5",
"money": "-110",
"context": "current"
}
},
"team-stats": {
"score": "0"
}
}, {
"team-metadata": {
"alignment": "Away",
"openNum": "525",
"nss": "525",
"name": {
"full": "South Carolina"
}
},
"wagering-stats": {
"wagering-straight-spread": {
"bookmaker-name": "BetOnline",
"active": "true",
"line": "-1.5",
"money": "-110",
"context": "current"
}
},
"team-stats": {
"score": "0"
}
}]
}],
"sports-meta-data": {
"doc-time": "42353.5979256944"
}
}
}
server.js
Meteor.startup(function () {
Meteor.methods({
sportsFeed:function(){
//console.log(JSON.parse(Assets.getText('ncaab.json')));
var feed = {};
var feed = JSON.parse(Assets.getText("ncaab.json"));
return feed;
}
});
});
Template.html
<template name="tabsOne">
<p>{{display}}</p>
</template>
Template.js
Template.tabsOne.helpers({
display: function(){
Meteor.call('sportsFeed', function(error, result){
if(error){
console.log("error", error);
}
if(result){
console.log('success');
}
});
}
});
If the json file is from your local, thinking about save it into Mongo and then publish it to the client
First, you need to create a collection called SportContent and on the server side, just make
SportContent.insert(JSON.parse(Assets.getText("ncaab.json")));
and then, do the normal publication to the client
If the json file is not on your local side (as in, you get it from rest call service), use wrapAsync to wrap the Http.call, then trigger the rest call and return the result. On your client side, you will get the response
Example on the server side to connect to the rest api
Meteor.methods({
'updateFeed': function () {
var httpCall = Meteor.wrapAsync(HTTP.call);
var result = httpCall('GET', url, {headers: headers});
....
}
});

AngularJS display JSON data in table

I am using AngularJS with RESTAPI, I am able to get the customers data sent from server in a JSON format. My Angular code snippet as below:
app.factory("services", ['$http', function($http) {
var serviceBase = '/api/album';
var obj = {};
obj.getCustomers = function(){
return $http.get(serviceBase);
};
return obj;
}]);
app.controller('listCtrl', function ($scope, services) {
services.getCustomers().then(function(data){
alert(JSON.stringify(data.data));
$scope.customers = data.data;
});
});
Here is my JSON data:
{
"data": [
{
"id": "1",
"artist": "Gotye75",
"title": "Making Mirrors7"
},
{
"id": "100",
"artist": "ytttt5",
"title": "1231"
},
{
"id": "101",
"artist": "65",
"title": "565444555"
},
{
"id": "102",
"artist": "6",
"title": "6"
},
{
"id": "103",
"artist": "y",
"title": "yy"
},
{
"id": "104",
"artist": "ty",
"title": "yt"
},
{
"id": "109",
"artist": "ytrer",
"title": "yt"
}
]
}
I am able to display the JSON data in table if my JSON does not contain the "data" hear. However if my jSON data comes with "data" header, it is unable to display. I am asking, what are the solution in Angular to parse the JSON object.
For example if it is in BackboneJS, i can simply do
parse: function (response) {
//alert(JSON.stringify(response.data));
return response.data;
}
How can i do it in Angular?
$http resolves its promises with a response object. The data is accessed via the response object's data property. So to get to the array, you'd have to use
$scope.customers = data.data.data;
$http's promise is enhanced with a .success() convenience method which unwraps the response object...
services.getCustomers().success(function(data){
alert(JSON.stringify(data.data));
$scope.customers = data.data;
});
I solved it by
app.controller('listCtrl', function ($scope, services) {
services.getCustomers().then(function(data){
//notice that i added the third data
$scope.customers = data.data.data;
});
});

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);
});

evaluating json object returned from controller and attaching it to prepopulate attribute of tokeninput

I am using loopjs tokeninput in a View. In this scenario I need to prePopulate the control with AdminNames for a given Distributor.
Code Follows :
$.getJSON("#Url.Action("SearchCMSAdmins")", function (data) {
var json=eval("("+data+")"); //doesnt work
var json = {
"users": [
eval("("+data+")") //need help in this part
]
}
});
$("#DistributorCMSAdmin").tokenInput("#Url.Action("SearchWithName")", {
theme: "facebook",
preventDuplicates: true,
prePopulate: json.users
});
There is successful return of json values to the below function. I need the json in the below format:
var json = {
"users":
[
{ "id": "1", "name": "USER1" },
{ "id": "2", "name": "USER2" },
{ "id": "3", "name": "USER3" }
]
}

Extract Json data on client side

I have following JSON data coming to client. I need to extract the data somehow so I can loop through it to get all name & count values.
{
"summarydata": {
"rows": [
{
"name": "Cisco0 Webinar US",
"count": "1"
},
{
"name": "Resource Nation CC",
"count": "1"
},
{
"name": "test",
"count": "10"
},
{
"name": "test",
"count": "2"
},
{
"name": "Vendor Seek",
"count": "1"
}
]
}
}
$.extend($.jgrid.defaults,
{ datatype: 'jsonstring' },
{ ajaxGridOptions: { contentType: "application/json",
success: function (data, textStatus) {
if (textStatus == "success") {
var thegrid = $("#BuyBackGrid")[0];
thegrid.addJSONData(data.data);
var summaryresult = $.parseJSON(data.summarydata.rows[0]);
alert(summaryresult );// this gives me null
alert(data.summarydata.rows[0].name); //this gives me first name element which is "Cisco0 Webinar US" in my case.
// alert($.parseJSON(data).summarydata.rows[0].name);
}
} //end of success
}//end of ajaxGridOptions
});
Leveraging jQuery...
The $.getJSON() function parses a local JSON file and returns it as an object.
$.getJSON("myJSON.js", function(json){
alert(json.summarydata.rows[0].name);
});
You could also just do this, using the JSON library for javascript (the object is also standard in most recent browsers).
alert(JSON.parse(myJSONString).summarydata.rows[0].name);