I am trying to get data from a JSON file to display in my AngularJS app using $http.get(...). When I run an alert with JSON.stringify, the alert says 'undefined'. Here is my code:
JS
var pplApp = angular.module('pplApp', [ 'ngAnimate', 'ngSanitize', 'utilServices' ]);
pplApp.controller('pplCtrl', function($scope, $http) {
$http.get('people.json').then(function(data) {
alert(JSON.stringify(data.People));
$scope.peoples = data.People;
});
});
JSON
{
"People": [
{
"name": "Andrew Amernante",
"rating": 3,
"img": "http://www.fillmurray.com/200/200",
"Description": "Glutenfree cray cardigan vegan. Lumbersexual pork belly blog, fanny pack put a bird on it selvage",
"Likes": [
"Dogs",
"Long walks on the beach",
"Chopin",
"Tacos"
],
"Dislikes": [
"Birds",
"Red things",
"Danish food",
"Dead Batteries"
]
}
]
}
What am I missing?
Update: Here is my app in Plunker
您不应将点运算符与JSON.stringify一起使用,因为它只是一个字符串,请将其更改为
alert(JSON.stringify(data));
The result is a response object (not the data itself). You can access the data as response.data
pplApp.controller('pplCtrl', function($scope, $http) {
$http.get('people.json').then(function(response) {
alert(JSON.stringify(response.data.People));
$scope.peoples = response.data.People;
});
});
Here data is a JSON string not object, so you can not use data.People , instead you just need to pass data to JSON.parse .
var pplApp = angular.module('pplApp', [ 'ngAnimate', 'ngSanitize', 'utilServices' ]);
pplApp.controller('pplCtrl', function($scope, $http) {
$http.get('people.json').then(function(data) {
var response = JSON.parse(data);
$scope.peoples = response.People;
});
});
I checked with your json string and works using following code.
var json = '{"People": [{"name": "Andrew Amernante","rating": 3,"img": "http://www.fillmurray.com/200/200","Description": "Glutenfree cray cardigan vegan. Lumbersexual pork belly blog, fanny pack put a bird on it selvage","Likes": ["Dogs","Long walks on the beach","Chopin","Tacos"],"Dislikes": ["Birds","Red things","Danish food","Dead Batteries"]}]}';
var response = JSON.parse(json);
$scope.peoples = response.People;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.