Access multiple items in multiple arrays from JSON using AngularJS - json

I'm building a phone directory app using AngularJS with JSON data. I'm new to AngularJS and JSON.
I went through the "Phonecat" tutorial on the AngularJS site and was able to build a test directory with JSON data that was similar to the tutorial.
I hit a roadblock using what I learned there and trying to build something with real data; the JSON objects have multiple arrays and I've not been able to figure out how to access the data in the arrays...
I tried to replicate my issue here: http://jsfiddle.net/4ykNX/
Thanks in advance!
//employee.json
{
"resultTruncated": false,
"containsSecureData": false,
"entries": [
{
"type": "employee",
"firstName": "Any",
"lastName": "One",
"address": [
{
"streetOne": "123 Long Street",
"streetTwo": "Big Building",
"streetThree": "Room 456",
"city": "City",
"state": "ST",
"zip": "12345"
}
],
"phone": [
{
"area": "111",
"number": "222-3333",
"extn": "444"
}
],
"email": "any#one.edu"
}
]
}

You are trying to set $scope.employees to data, when it should be data.entries
'use strict';
function EmpListCtrl($scope, $http) {
$http.get('employees.json').success(function(data) {
$scope.employees = data.entries;
});
}
Then you need to reference employee.phone instead of phone:
<div ng-app>
<div ng-controller="EmpListCtrl">
<h1>Employees</h1>
<ul>
<li ng-repeat="employee in employees">
{{employee.lastName}}, {{employee.firstName}}<br/>
{{employee.email}}
<ul>
<li ng-repeat="num in employee.phone">
{{num.area}}-{{num.number}}-{{num.extn}}
</li>
</ul>
</li>
</ul>
</div>
</div>
Here's a plnkr: http://plnkr.co/edit/L2nMu0?p=preview

Related

How to display item of nested json array in component using Angular 7

How can I display "empName" and other details of this JSON in my table component in loop?
I'm using a third party API which provides a nested JSON object in return when I send employerID to the API URL.
After subscribing I'm storing the response in a var "AllPostedJobs"
{
"status": "All Jobs",
"result": [
{
"_id": "5c90fd3cfc7f3b0017803319",
"job_title": "Web Designer",
"job_desc": "test description ...",
"location": "Mangalore",
"experiance": "Freshers",
"job_type": "Full-Time",
"salary_package": "3L",
"job_keywords": "Photoshop, Illustrator",
"email_id": "hr#shreemithra.com",
"employerID": "5c7e99c2a7a9eb00174de2b2",
"company_name": "Shreemithra Designs",
"AppliedStudentDetails": [
{
"_id": "5c9393c1a918d60017de7e55",
"empName": "Anup",
"empID": "5c939375a918d60017de7e53",
"job_title": "Web Designer"
}
],
"__v": 1
},
{
"_id": "5c913570cb78a100177ab23a",
"job_title": "Full Stack Developer",
"job_desc": "htjhsv dhsd jh jds fjshgdfkhsdmhfd;lw eiwiwemsd. This is a sample job description.",
"location": "Pune",
"experiance": "2 Years",
"job_type": "Part-Time",
"salary_package": "8L - 10L PA",
"job_keywords": "Angular, Node JS, React, HTML5. CSS3",
"email_id": "info#shreemithra.com",
"employerID": "5c7e99c2a7a9eb00174de2b2",
"company_name": "Shreemithra Designs",
"AppliedStudentDetails": [
{
"_id": "5c9393c9a918d60017de7e56",
"empName": "Anup",
"empID": "5c939375a918d60017de7e53",
"job_title": "Full Stack Developer"
},
{
"_id": "5ca60fa5ba17730017182ca8",
"empName": "Amit Pateriya",
"empID": "5c7795acfd39640017ca4c37",
"job_title": "Full Stack Developer"
}
],
"__v": 2
}
]
}
The simplest way is when you receive data from api then send it to a
function then apply multiples loop alter your data by add keys in
front of data and that values for example
var data = [{"id":1, "name":"smith","applicant":{"roll": 32,"class":10}}];
data[0].applicantRoll = data[0].applicant.roll;
data[0].applicantClass = data[0].applicant.class;
now you can apply *ngfor easily, try this.
You can bind display data by binding controls in an HTML template to properties of your component.
The easiest way to display a component property is to bind the property name through interpolation. With interpolation, you put the property name in the view template, enclosed in double curly braces:{{AllPostedJobs.status}}.
<div id="result-container" *ngFor="let record of AllPostedJobs.result">
<another-component [record]= "record"></another-component>
</div>
Or depending on your need you can hand over entire result data to another-component.
Now your another-component, should have #Input defined to handle the incoming data:
export class AnotherComponent {
#Input() record: Array<any>;
In your another-component template:
<div *ngFor="let student of record?.AppliedStudentDetails">
<span>{{student.empName}}</span>
<span [innerText]="student.job_title"></span>
</div>

Accessing the child of a child in a JSON with Handlebars.js

I'm having no trouble accessing the initial child of the parent object in a json, however, I cannot seem to figure out what the format for accessing the child of a child is. I'm currently using dot notation as described in the handlebars.js documentation.
My html with handlebars.js implemented (the 'Fees' aren't showing correctly, they show up as [object Object]):
{{#options}}
{{#company_base}}
<div>
<h1>{{name_full}}</h1><b>AM Best Rating</b>: {{ambest_rating}}
<p><b>Type</b>: {{business_type}}</p>
<p><b>Fees</b>:
<ol>
<li><b>Type</b>: {{../..options.fees.type}}</li>
<li><b>Name</b>: {{../..options.fees.name}}</li>
</ol>
</p>
</div>
{{/company_base}}
{{/options}}
My mock JSON:
{
"options": [{
"company_base": {
"business_type": "Life, Accident, and Health",
"established_year": 1998,
"med_supp_state_market_data": [{
"market_share": 0.63490064689900005,
"state": "AK",
"lives": 8041,
"premiums": 14714825,
"claims": 11649263
}, {
"market_share": 0.34445359987700003,
"state": "WY",
"lives": 14916,
"premiums": 30178554,
"claims": 24281001
}],
"underwriting_data": [],
"med_supp_national_market_data": {
"market_share": 0.315510079562,
"state": null,
"lives": 3723184,
"premiums": 8276072271,
"claims": 6436017316
},
"customer_complaint_ratio": 0.0013368044250809999,
"ambest_outlook": "Stable",
"name_full": "Major Health Partners of the Wind",
"ambest_rating": "A",
"parent_company": "aghzfmNzZ2sdfZWRfc3VwcA",
"last_modified": "2017-01-16T12:28:17.591830",
"customer_satisfaction_ratio": 0.83666666666699996,
"default_resources": {
"final-expense-life": {
"e_app_link": ""
},
"medicare-advantage": {
"e_app_link": ""
},
"medicare-supplement": {
"e_app_link": "sdf"
},
"hospital-indemnity": {
"e_app_link": ""
},
"dental": {
"e_app_link": ""
}
},
"key": "assdfsdfVwcA",
"parent_company_base": {
"established_year": 1998,
"code": "707",
"name": "Space Insurance",
"key": "asfdf",
"last_modified": "2016-11-11T16:42:52.240940"
},
"sp_rating": "AA-",
"naic": "79413",
"type": "STOCK",
"name": "Spacewomen Insurance"
},
"has_pdf_app": true,
"rate": {
"quarter": 23841,
"annual": 92964,
"semi_annual": 47682,
"month": 7747
},
"rating_class": "Standard",
"fees": [{
"name": "corgi discount",
"type": "buddy"
}]}
Here is a live example of my issue.
It is not the "child of a child" that you are having trouble accessing, but a sibling property that is of the array type.
There are two problems with your example. First, fees is on the same level as company_base. When you are within the {{#company_base}} {{/company_base}} tags you are within the context of the company_base object, so must step-up one level in order to access its siblings. The correct path would be: {{../fees}}.
Your second issue is that fees is an array. You might want to {{#each}} over this array, but if you want only the first object, then you can access it like: {{fees.0.type}}.
This means that your template should be updated with the following:
<li><b>Type</b>: {{../fees.0.type}}</li>
<li><b>Name</b>: {{../fees.0.name}}</li>
That should do the trick. However, I would like to recommend an alternative way of writing your template. I would eliminate the need to step-up a level to get the fees object by removing the {{#company_base}} {{/company_base}} tags. This will mean that you are at the level of the current object in the options array and you can use dot notation to access its descendant properties. The updated template would look like the following:
{{#each options}}
<div>
<h1>{{company_base.name_full}}</h1>
<b>AM Best Rating</b>: {{company_base.ambest_rating}}
<p><b>Type</b>: {{company_base.business_type}}</p>
<p>
<b>Fees</b>:
<ol>
<li><b>Type</b>: {{fees.0.type}}</li>
<li><b>Name</b>: {{fees.0.name}}</li>
</ol>
</p>
</div>
{{/each}}
Note: I am opting for the more explicit {{#each options}} over {{#options}}.
I have created an example fiddle here.

parsing data from JSON

I am making an AJAX call to a JSON file containing thumbnail images and website urls, I am then listing each out using AngularJS directive ng-repeat to list. The problem is the thumbnails and website urls are no longer populating my page. I reformatted my JSON file data into an array because I will be adding multiple arrays to my JSON file that will contain different objects to be used on other pages throughout the website.
JSON:
{"websites":[
{
"thumbnail": "thumbnail1.jpg",
"website": "http://somewebsite.com"
},
{
"thumbnail": "thumbnail2.jpg",
"website": "http://somewebsite.com"
},
{
"thumbnail": "thumbnail3.jpg",
"website": "http://somewebsite.com"
}
]}
Angular:
angular.module('myApp')
.constant("dataUrl", "../json/data.json")
.controller("websitesController", function($scope, $http, dataUrl){
$scope.data ={};
$http.get(dataUrl)
.success(function(data){
$scope.data.projects = data;
})
.error(function(error){
$scope.data.error = error;
});
});
HTML:
<ul ng-controller="websitesController">
<li ng-repeat="item in data.projects">
<img ng-src="{{item.thumbnail}}" />
<div>
<a ng-href="{{item.website}}" target="_blank"><b>Website</b></a>
</div>
</li>
<ul>
Your JSON data has a key called websites that is storing an array of websites. You are adding that object with the websites key as your $scope.data.projects. To access the array of websites, you need to look into that object, i.e., you should assign $scope.data.projects to data.websites. Change your success handler as follows:
.success(function(data){
$scope.data.projects = data.websites;
})
EDIT: data examples --
Your response data looks like this:
{"websites":[
{
"thumbnail": "thumbnail1.jpg",
"website": "http://somewebsite.com"
},
{
"thumbnail": "thumbnail2.jpg",
"website": "http://somewebsite.com"
},
{
"thumbnail": "thumbnail3.jpg",
"website": "http://somewebsite.com"
}
]}
But, you want it to look like this (parsed too) in order to use it in your ng-repeat:
[
{
"thumbnail": "thumbnail1.jpg",
"website": "http://somewebsite.com"
},
{
"thumbnail": "thumbnail2.jpg",
"website": "http://somewebsite.com"
},
{
"thumbnail": "thumbnail3.jpg",
"website": "http://somewebsite.com"
}
]
It should be $scope.data.projects=data.websites;

Displaying JSON data in jquery Datatable

I have a json message in the below format returned from the server. I using jquery data tables to display the data in the table. I am getting some error when trying to use jquery data table. Please let me know where I am going wrong in the configuration of jquery data table to display the below json format. The configuration for jquery data table along with the json data is given below:
$(function () {
$('#dataTable').dataTable( {
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"aaData": [
{
"links": [
{
"rel": "self", // the first column data which should be displayed as link
"href": "http://localhost:8080/16"
}
],
"Country": "INDIA",
"state": "Karnataka",
"city": "Bangalore",
"cityId": 16
},
{
"links": [
{
"rel": "self",
"href": "http://localhost:8080/17"
}
],
"Country": "INDIA",
"state": "Tamilnadu",
"city": "Chennai",
"cityId": 17
}
]
});
A little look up on the jquery datatables documentation helped me to get to the solution. The trick is to use the mData and then map the columns to the attributes from the json. The link for the same is mentioned below:
http://datatables.net/release-datatables/examples/server_side/object_data.html

Json parsing problems with node.js

I am new to programming and I am trying to learn node.js and CoffeeScript. I have read a few books and watched some screencasts. And now I have started to code. Now I faced my first problem and was not able to solve it with Google. Already lost a few hours and I am stuck. Maybe someone can give me a light.
Here is the problem. I have this json file:
{
"title": "title",
"pages": [
{ "name": "Page1", "url": "#Page1", "class": "class", "template":"templateName" },
{ "name": "Page2", "url": "#Page2", "class": "class", "template":"templateName" },
{ "name": "Page3", "url": "#Page3", "class": "class", "template":"templateName" },
{ "name": "Page4", "url": "#Page4", "class": "class", "template":"templateName" },
{ "name": "Page5", "url": "#Page5", "class": "class", "template":"templateName" }
]
}
and the code to get the json file is
configFile = require(file.json)
If I do
console.log(configFile.pages)
I can get the correct information.
But if I do
console.log(configFile.pages.template[0])
I get an undefined error.
Can anyone give me a hand?
configFile.pages[0].template
it's your structure :)
template is not an array, pages is. So use this:
console.log(configFile.pages[0].template);