Note: In this example, I am using AngularJS version 1.5.0.
JSON Data in a File
The file name is birds.json. You can create a JSON file using the Notepad. Its very simple.
[ { "ID": "001", "Name": "Eurasian Collared-Dove", "Type": "Dove" }, { "ID": "002", "Name": "Bald Eagle", "Type": "Hawk" }, { "ID": "003", "Name": "Cooper's Hawk", "Type": "Hawk" }, { "ID": "004", "Name": "Bell's Sparrow", "Type": "Sparrow" }, { "ID": "005", "Name": "Mourning Dove", "Type": "Dove" }, { "ID": "006", "Name": "Rock Pigeon", "Type": "Dove" }, { "ID": "007", "Name": "Abert's Towhee", "Type": "Sparrow" }, { "ID": "008", "Name": "Brewer's Sparrow", "Type": "Sparrow" }, { "ID": "009", "Name": "Canyon Towhee", "Type": "Sparrow" }, { "ID": "010", "Name": "Black Vulture", "Type": "Hawk" } ]
Open a Notepad, copy the above JSON data in the Notepad, and save by file using .json extension, that is, sample.json.
1) Parse JSON file and Populate Data to a Table in AngularJS
I’ll show you how populate the Parsed JSON data to a <table> element and in a <ul> list. However, first I am using the <table> to show the data.
In my markup, I have the ng-repeat directive, which loop through a $scope property called list.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script> <style> table { width: auto; } table, th, td { border: solid 1px #DDD; border-collapse: collapse; padding: 2px 3px; text-align: center; } </style> </head> <body> <div ng-app="myApp" ng-controller="myController"> <table> <tr> <th>ID</th> <th>Bird Name</th> <th>Type of Bird</th> </tr> <tr ng-repeat="birds in list"> <td>{{birds.ID}}</td> <td>{{birds.Name}}</td> <td>{{birds.Type}}</td> </tr> </table> </div> </body> <!--The Controller--> <script> var app = angular.module('myApp', []); app.controller('myController', function ($scope, $http) { var request = { method: 'get', url: 'https://www.encodedna.com/angularjs/tutorial/birds.json', dataType: 'json', contentType: "application/json" }; $scope.arrBirds = new Array; $http(request) .success(function (jsonData) { $scope.arrBirds = jsonData; $scope.list = $scope.arrBirds; }) .error(function () { }); }); </script> </html>
👉 How to populate JSON array to a SELECT DropDownList using AngularJS ng-options
The $scope.list property will have the extracted JSON data. I am using AngularJS $http Service to fetch the data using the GET method.
2) Parse JSON file and Show Data with <ul> and <li> in AngularJS
Similarly, you can show the parsed JSON data using HTML <ul> and <li> lists. For example,
<body> <div ng-app="myApp" ng-controller="myController"> <ul ng-repeat="birds in list"> <li>{{ birds.ID + ' - ' + birds.Name + ' - ' + birds.Type }}</li> </ul> </div> </body>
You will need to add some style to the <ul> list.
<style> ul { list-style:none; font:17px Calibri; margin:1px 0; padding:0; } </style>
The controller or the script remains the same.