JSON parsing and displaying in different tables using Angular JS - javascript

I'm new to Angular JS here.
can any one please help me how to parse and display the Json Data in different tables using Angular JS
[
{
"id": 0,
"isActive": false,
"balance": 1025.00,
"picture": "http://www.placekitten.com/50/50",
"age": 25,
"name": "Daisy Mcneil",
"gender": "female",
"company": "Verbus",
"email": "daisymcneil#verbus.com",
"phone": "+1 (936) 586-3983",
"address": "849 Newkirk Placez, Laurelton, Nevada, 1086",
"registered": "2012-07-15T13:46:25 +07:00",
"friends": [
{
"id": 0,
"name": "Debra Blair"
},
{
"id": 1,
"name": "Henry Avila"
},
{
"id": 2,
"name": "Jody Stark"
}
],
"service": "cherry"
},
{
"id": 1,
"isActive": true,
"balance": -2884.00,
"picture": "http://www.placekitten.com/50/50",
"age": 23,
"name": "Schroeder Atkinson",
"gender": "male",
"company": "Twiggery",
"email": "schroederatkinson#twiggery.com",
"phone": "+1 (861) 449-2254",
"address": "259 Highland Avenue, Riner, Vermont, 905",
"registered": "1998-01-17T08:16:34 +08:00",
"friends": [
{
"id": 0,
"name": "Mendoza Figueroa"
},
{
"id": 1,
"name": "Lenore Morales"
},
{
"id": 2,
"name": "Winifred Bowen"
}
],
"service": "lemon"
}
]
I want to display each JSON object in the different table with a buttion which toggles the table in the html.
the above is the JSON data available...
thanks in advance.
The skeleton for the code is available here https://github.com/50Cubes/WebappTest

This is the code for index.html file -
<!doctype html>
<html>
<head>
<title>Page Title</title>
<script src="main.js"></script>
</head>
<body>
<div ng-app="MyApp">
<div ng-controller="ViewJson">
<table>
<th>
<td>id</td>
<td>isActive</td>
<td>balance</td>
<td>picture</td>
<td>age</td>
<td>name</td>
<td>gender</td>
<td>company</td>
<td>email</td>
<td>phone</td>
<td>address</td>
<td>registered</td>
<td>service</td></th>
<tr ng-repeat="post in posts">
<td>{{post.id}}</td>
<td>{{post.isActive}}</td>
<td>{{post.balance}}</td>
<td>{{post.picture}}</td>
<td>{{post.age}}</td>
<td>{{post.name}}</td>
<td>{{post.gender}}</td>
<td>{{post.company}}</td>
<td>{{post.email}}</td>
<td>{{post.phone}}</td>
<td>{{post.address}}</td>
<td>{{post.registered}}</td>
<td>{{post.service}}</td></tr></table>
</div>
</div>
</body>
</html>
This is the code for main.js file. Here I am assuming that the name of json file is posts.js -
var app=angular.module('MyApp',[]);
function ViewJson($scope, $http)
{$http({method: 'POST', url: 'js/posts.json'}).success(function(data)
{$scope.posts = data;});
}

Related

JSON Response Parsing Error - Javascript

I have the following JSON response coming from an API.
{
"status": true,
"cakes": {
"7689": {
"id": 7689,
"flavor": "chocolate",
"cookDetails": {
"id": 101,
"firstName": "Name1",
"lastName": "LastName1"
}
},
"7690": {
"id": 7690,
"flavor": "vanilla",
"cookDetails": {
"id": 102,
"firstName": "Name2",
"lastName": "LastName2"
}
}
}
}
Language I'm using to parse this JSON: Javascript
Framework: ReactNative
My question is:
1. Is the JSON format correct?
2. If yes, then how do I parse it (NOTE: I don't know the value of id in cakes until I parse it)?
PS: New to the framework. Big thanks.
Try using this,
{
"status": true,
"cakes": [{
"id": 7689,
"flavor": "chocolate",
"cookDetails": {
"id": 101,
"firstName": "Name1",
"lastName": "LastName1"
}
}, {
"id": 7690,
"flavor": "vanilla",
"cookDetails": {
"id": 102,
"firstName": "Name2",
"lastName": "LastName2"
}
}]
}
for ReactNative check this :https://facebook.github.io/react-native/docs/network.html
http://www.9lessons.info/2017/04/react-native-json-parsing-and-helper.html
Note below code HTML JavaScript for your understanding.
var obj = JSON.parse('{"status": true,"cakes": [{"id": 7689,"flavor": "chocolate","cookDetails": {"id": 101,"firstName": "Name1","lastName": "LastName1"}},{"id": 7690,"flavor": "vanilla","cookDetails": {"id": 102,"firstName": "Name2","lastName": "LastName2"}}]}');
<!DOCTYPE html>
<html>
<body>
<h2>Create Object from JSON String</h2>
<p id="demo"></p>
<script>
var obj = JSON.parse('{"status": true,"cakes": [{"id": 7689,"flavor": "chocolate","cookDetails": {"id": 101,"firstName": "Name1","lastName": "LastName1"}},{"id": 7690,"flavor": "vanilla","cookDetails": {"id": 102,"firstName": "Name2","lastName": "LastName2"}}]}');
document.getElementById("demo").innerHTML = obj.cakes[0].id +", "+ obj.cakes[0].flavor+", "+obj.cakes[0].cookDetails.id+", "+obj.cakes[0].cookDetails.firstName+", "+obj.cakes[0].cookDetails.lastName;
</script>
</body>
</html>
Here is valid JSON(just extra commas were removed):
{
"status": true,
"cakes": {
"7689": {
"id": 7689,
"flavor": "chocolate",
"cookDetails": {
"id": 101,
"firstName": "Name1",
"lastName": "LastName1"
}
},
"7690": {
"id": 7690,
"flavor": "vanilla",
"cookDetails": {
"id": 102,
"firstName": "Name2",
"lastName": "LastName2"
}
}
}
}
You can parse it with plain JSON.parse call

Angular JS: How to use ng-repeat for complex objet

I have a complex object coming from the web service as shown below, how to display PatientId and description, if anyone have any good idea, please help me thru it.:
$scope.myData = {"PatientSearchResponse": {
"pageNumber": 1,
"pageSize": 50,
"patDataBean": [
{
"gender": {
"code": "male",
"description": "Male",
"type": "gender"
},
"patDateofBirth": "1997/06/19",
"patFirstName": "aman",
"patLastName": "elvis",
"patSurvivalStat": {
"code": "A",
"description": "Alive",
"type": "patient_status"
},
"patientIdentifier": {
"OID": "589a9cf6-4513-49e1-bd5c-c7363849ed93",
"organizationId": {
"PK": 54,
"siteName": "CTRP"
},
"patientId": "1"
}
},
{
"gender": {
"code": "male",
"description": "Male",
"type": "gender"
},
"patDateofBirth": "2001/07/18",
"patFirstName": "Elvis",
"patLastName": "Harvey",
"patSurvivalStat": {
"code": "dead",
"description": "Dead",
"type": "patient_status"
},
"patientIdentifier": {
"OID": "151d0222-3726-40ee-8f69-0a6800727607",
"organizationId": {
"OID": "83d09227-9c65-4d7b-94da-baaf5c07b38a",
"siteName": "Texas"
},
"patientId": "100"
}
}]}}
In my HTML I am using ng-repeat as:
<td ng-repeat="(key, value) in grid.columns">
<div>
<p >{{row[key]}}</p>
</div>
</td>
my JS file as:
myDataContainer = $scope.myData.PatientSearchResponse.patDataBean;
$scope.grid.columns = {patientIdentifier: "Patient Id",patFirstName: "First Name",patLastName: "Last Name",patDateofBirth: "Date of Birth",patSurvivalStat: "Description"};
angular.forEach(myDataContainer, function (values, index) {
$scope.grid.rows.push(values);
});
Why you can just do this :
<td ng-repeat="pat in myData.PatientSearchResponse.patDataBean">
{{pat.patientIdentifier}} - {{pat.patSurvivalStat.description}}
</td>
Try this man:
angular.module('app', [])
.controller('Controller', ['$scope', function($scope) {
$scope.myData = {"PatientSearchResponse": {
"pageNumber": 1,
"pageSize": 50,
"patDataBean": [
{
"gender": {
"code": "male",
"description": "Male",
"type": "gender"
},
"patDateofBirth": "1997/06/19",
"patFirstName": "aman",
"patLastName": "elvis",
"patSurvivalStat": {
"code": "A",
"description": "Alive",
"type": "patient_status"
},
"patientIdentifier": {
"OID": "589a9cf6-4513-49e1-bd5c-c7363849ed93",
"organizationId": {
"PK": 54,
"siteName": "CTRP"
},
"patientId": "1"
}
},
{
"gender": {
"code": "male",
"description": "Male",
"type": "gender"
},
"patDateofBirth": "2001/07/18",
"patFirstName": "Elvis",
"patLastName": "Harvey",
"patSurvivalStat": {
"code": "dead",
"description": "Dead",
"type": "patient_status"
},
"patientIdentifier": {
"OID": "151d0222-3726-40ee-8f69-0a6800727607",
"organizationId": {
"OID": "83d09227-9c65-4d7b-94da-baaf5c07b38a",
"siteName": "Texas"
},
"patientId": "100"
}
}]}}
}]);
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-controller="Controller">
<table>
<tr>
<th>Id</th>
<th>Description</th>
</tr>
<tr ng-repeat="m in myData.PatientSearchResponse.patDataBean">
<td>{{m.patientIdentifier.patientId}}</td>
<td>{{m.patSurvivalStat.description}}</td>
</tr>
</table>
</body>
</html>
Would be more practical to make columns an array of objects with standardized keys
$scope.grid.columns = [
{property : 'patientIdentifier', heading : "Patient Id"},
{property : 'patFirstName', heading : "First Name"},
{property : 'patLastName', heading : "Last Name"},
{property : 'patDateofBirth', heading : "Date of Birth"},
{property : 'patSurvivalStat', heading : "Description"}
]
Then use those to set both headings and content
<table>
<thead>
<tr>
<th ng-repeat="col in grid.columns">{{::col.heading}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in myData.patDataBean">
<td ng-repeat="col in grid.columns">{{::item[col.property]}}</td>
</tr>
</tbody>
</table>

Unable to Create table through json object using Angularjs

Click here to see For Converted Json Object
Please Read My question very clear
Hi in my code below I am trying to convert xml Data to Json Object. using converted Json Object i am trying to create a table using angularjs.
so here the problem is i am able to bind complete converted json object {{employeeList}} but failed to load individual atttribute of json object i.e.,{{employee.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 what I expected, but when I assign the direct result
i.e,$scope.Employees=response.data;It is not working what might be the issue.here the response.data is nothing but success function result we get here
<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;
}
})
.then(function (response) {
$scope.Employees = response.data;
console.log($scope.Employees);
});
});
</script>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="httpApp">
<div ng-controller="httpController">
<div ng-repeat="employeeList in Employees">
{{employeeList}}
<table>
<tr ng-repeat="employee in Employees.Employee">
<td>{{employee.EmpId}}</td>
<td>{{employee.Name}}</td>
<td>{{employee.Phone._Type}}</td>
<td>{{employee.Phone.__text}}</td>
<td>{{employee.Address.Street}}</td>
<td>{{employee.Address.State}}</td>
<td>{{employee.Phone.Zip}}</td>
<td>{{employee.Phone._text}}</td>
<td>{{employee.Address.Country}}</td>
</tr>
</table>
</div>
</div>
Click here..For Converted Json Object
Here is a simple example based on the json provided:
HTML
<html xmlns="http://www.w3.org/1999/xhtml" ng-app="myApp">
<head runat="server">
<title></title>
</head>
<body ng-controller="myController">
<div>
<table>
<thead>
<tr>
<th>EmpId</th>
<th>Name</th>
<th>Sex</th>
<th>Phone</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="employee in json.Employee">
<td>{{employee.EmpId}}</td>
<td>{{employee.Name}}</td>
<td>{{employee.Sex}}</td>
<td>{{employee.Phone[0].__text}}</td>
<td>{{employee.Address.Street}}</td>
</tr>
</tbody>
</table>
</div>
<script src="scripts/angular.js"></script>
<script src="scripts/app.js"></script>
</body>
</html>
JavaScript
(function () {
angular.module('myApp', [])
.controller('myController', function ($scope) {
$scope.json = { "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" } }] };
})
}());
You should change your code to this.
<div ng-app><div ng-controller="httpController">
<div>
<table>
<tr ng-repeat="employee in Employees.Employee">
<td>{{employee.EmpId}}</td>
<td>{{employee.Name}}</td>
<td>{{employee.Phone._Type}}</td>
<td>{{employee.Phone.__text}}</td>
<td>{{employee.Address.Street}}</td>
<td>{{employee.Address.State}}</td>
<td>{{employee.Phone.Zip}}</td>
<td>{{employee.Phone._text}}</td>
<td>{{employee.Address.Country}}</td>
</tr>
</table>
</div>
There is another issue in your code. The response data resides in response.data, so besides your JSON being valid or not, you should use the following assignment:
$scope.Employees = response.data
Extra comment after my previous answer about response.data, because I don't see the right answer about your JSON object here yet, full answer:
ng-repeat expects a list of items, which you don't provide. Remove the encapsulating 'Employee' part from your JSON, like this:
$scope.Employees = [
{"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" } },
{"EmpId": "5", "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" } }
]
(I've added an extra Employee with ID 5 here, but it will work with only one employee as well, as long it's a list, objects ({}) in a list ([]).
With this JSON object you can do the following:
<tr ng-repeat="employee in Employees">
<td>{{ employee.EmpId }}</td>
<td>{{ employee.Name }}</td>
<td>etc ...</td>
</tr>
Make sure your JSON is set up like this, encapsulating comma separated objects within a list.
Return this JSON format from your get request, and don't forget to fetch the data from response.data instead of response.

Using AngularJS with JSON objects in arrays nested within an array, how can I get the data into the html?

I am trying to get the JSON data into list.html as follows, but my attempts are failing. I have tried following patterns described in other similar posts, but haven't had any luck and haven't found a scenario with JSON data formatted exactly like mine. How do I get the fields like givenName, familyName, primaryTitle, phones[0].value, and photo.small to show up?
index.html:
<!doctype html>
<html lang="en" ng-app="directoryApp">
<head>
<meta charset="UTF-8">
<title>Directory</title>
<script src="lib/angular/angular.min.js"></script>
<script src="lib/angular/angular-route.min.js"></script>
<script src="lib/angular/angular-animate.min.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div ng-view></div>
</body>
</html>
list.html:
<ul ng-show="query">
<li ng-animate="'animate'" ng-repeat="person in people.people | filter: query | orderBy: peopleOrder:direction">
<img ng-src="images/{{person.photo.small}}" alt="Photo of {{person.name.givenName}}">
<div class="info">
<h2>{{person.name.givenName}}</h2>
<h3>{{person.primaryTitle}}, {{person.phones[0].value}}</h3>
</div>
</li>
</ul>
controllers.js:
var directoryControllers = angular.module('directoryControllers', ['ngAnimate']);
directoryControllers.controller('ListController', ['$scope', '$http', function($scope, $http) {
$http.get('js/directoryData.json').success(function(data) {
$scope.people = data;
$scope.peopleOrder = 'familyName';
});
}]);
app.js:
var directoryApp = angular.module('directoryApp', [
'ngRoute',
'directoryControllers'
]);
directoryApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/list', {
templateUrl: 'partials/list.html',
controller: 'ListController'
}).
otherwise({
redirectTo: '/list'
});
}]);
directoryData.json:
[
{
"uid": 15,
"name": "School of Programming",
"sortKey": 0,
"type": "Academic",
"address": {
"address1": "255 Foo St",
"address2": "Suite 310",
"city": "FooBar",
"state": "FB",
"postalCode": "90210"
},
"phones": [
{
"type": "Work",
"value": "555-1616"
},
{
"type": "Fax",
"value": "555-3620"
}
],
"people": [
{
"uid": "person1",
"classification": "Faculty",
"name": {
"givenName": "Roo",
"nickname": "",
"additionalName": "",
"familyName": "Baf"
},
"primaryTitle": "Part Time Worker",
"phones": [
{
"type": "Work",
"value": "555-1616"
},
{
"type": "Mobile",
"value": "555-1509"
}
],
"photo": {
"small": "/__media__/photos/foo_portrait_small.jpg",
"medium": "/__media__/photos/foo_portrait_medium.jpg",
"large": "/__media__/photos/foo_portrait_large.jpg"
}
},
{
"uid": "person2",
"classification": "Faculty",
"name": {
"givenName": "Foo",
"nickname": "",
"additionalName": "P.",
"familyName": "Bar"
},
"primaryTitle": "Blah",
"phones": [
{
"type": "Work",
"value": "555-3608"
},
{
"type": "Home",
"value": "555-4716"
}
],
"photo": {
"small": "/__media__/photos/portrait_small.jpg",
"medium": "/__media__/photos/portrait_medium.jpg",
"large": "/__media__/photos/portrait_large.jpg"
}
}
]
},
{
"uid": 16,
"name": "School of Coding",
"sortKey": 1,
"type": "Academic",
"address": {
"address1": "256 Foo St",
"address2": "Suite 311",
"city": "FooBar",
"state": "FB",
"postalCode": "90210"
},
"phones": [
{
"type": "Work",
"value": "555-1616"
},
{
"type": "Fax",
"value": "555-3620"
}
],
"people": [
{
"uid": "person3",
"classification": "Faculty",
"name": {
"givenName": "Boo",
"nickname": "",
"additionalName": "",
"familyName": "Far"
},
"primaryTitle": "Part Time Worker",
"phones": [
{
"type": "Work",
"value": "555-1617"
},
{
"type": "Mobile",
"value": "555-1508"
}
],
"photo": {
"small": "/__media__/photos/fooz_portrait_small.jpg",
"medium": "/__media__/photos/fooz_portrait_medium.jpg",
"large": "/__media__/photos/fooz_portrait_large.jpg"
}
},
{
"uid": "person4",
"classification": "Faculty",
"name": {
"givenName": "Too",
"nickname": "",
"additionalName": "P.",
"familyName": "Mar"
},
"primaryTitle": "Blah",
"phones": [
{
"type": "Work",
"value": "555-3607"
},
{
"type": "Home",
"value": "555-4717"
}
],
"photo": {
"small": "/__media__/photos/Xportrait_small.jpg",
"medium": "/__media__/photos/Xportrait_medium.jpg",
"large": "/__media__/photos/Xportrait_large.jpg"
}
}
]
}
]
You have an array of objects that each have a people property in them and that property value is an array.
Thus you need to use nested ng-repeat to first loop over the main array and within each iteration of that repeat, loop over the inner array
<ul ng-repeat="item in people">
<li ng-animate="'animate'" ng-repeat="person in item.people | filter: ...">

Using ember-data with custom serializer

I have you could say a non standard json api. I'm trying to use ember-data with it so from my reading around I need to create a serializer. I tried to find article online explaining how to do this but haven't found anything useful. I tried looking through the ember guides but also found nothing. Here is an example of my api:
collection of data:
{
"data": [
{
"id": 14,
"name": "company name",
"slug": "company-name",
"detail": {
"data": {
"id": 10,
"address": "10000 sw 16th ct",
"city": "Hollywood",
"state": "Alabama"
}
},
"employees": {
"data": [
{
"id": 17,
"first_name": "Peter",
"last_name": "Griffin",
"email": "company-name#Griffin.co"
},
{
"id": 18,
"first_name": "Robert",
"last_name": "Gornitz",
"email": null
}
]
}
},
{
"id": 8,
"name": "company name",
"slug": "company-name",
"detail": {
"data": {
"id": 8,
"address": "1000 n university dr",
"city": "Fort Lauderdale",
"state": "West Virginia"
}
},
"employees": {
"data": [
{
"id": 15,
"first_name": "Peter",
"last_name": "Griffin"
},
{
"id": 16,
"first_name": "Peter",
"last_name": "Griffin"
}
]
}
}
]
}
Here is an item with its relationships:
{
"data": {
"id": 1,
"name": "company name",
"slug": "company-name",
"detail": {
"data": {
"id": 1,
"address": "1515 n university dr",
"city": "Miami",
"state": "Mississippi"
}
},
"employees": {
"data": [
{
"id": 1,
"first_name": "Peter",
"last_name": "Griffin",
"email": "peter#email.com"
},
{
"id": 2,
"first_name": "Peter",
"last_name": "Griffin",
"email": "peter#email.com"
}
]
}
}
}
Are there any good resources showing me how to do this? Or should I just not use ember-data?
Just some tips from my side using Ember Data. I believe that you either have to be able the adapt api or write a deserializer:
1. Root Key "data"
Ember expects the root key to be the name of the model (e.g. "company"). You can handle that easily by creating an application serializer and overwriting the extractArray and extractSingle method by grabbing the payload from the 'data' key instead of the model "typeKey".
2. Embedded Records
You can use the EmbeddedRecordsMixin. But for that you will have to skip the root key "data" in the embedded records and directly include them (e.g. "employees": [ { id: "2", ... }, ... ])
I'd have a look at the EmbeddedRecordsMixin for that:
http://emberjs.com/api/data/classes/DS.EmbeddedRecordsMixin.html
http://emberjs.com/api/data/classes/DS.EmbeddedRecordsMixin.html#method_normalize
Hope that helps a little.

Categories

Resources