Chrillewoodz Chrillewoodz - 28 days ago 14
AngularJS Question

Unable to make a $http.get request to a local JSON file using Angular

I'm making a weather application where I need to grab a local JSON file from within my controller and then do stuff with the data. However, I can't get a local

$http.get
request to work for some reason. What should I do?

This is my current code:

var weatherApp = angular.module('weatherApp', []);

weatherApp.controller('weatherCtrl', function ($scope, $http) {
$scope.cities = [],
$scope.getCities = (function() {
$http.get('http://localhost:81/Webb/angular projekt/jsons/cities.json')
.success(function(data, status, headers, config) {

console.log(data);
})
.error(function(data, status, headers, config) {
console.log(status);
});
}())
}


Which gives me this error:

SyntaxError: Unexpected token { angular.js:11598
at Object.parse (native)
at oc (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:14:156)
at Yb (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:77:190)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:78:50
at s (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:7:302)
at Yc (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:78:32)
at c (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:79:165)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:112:343
at l.$eval (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:126:193)
at l.$digest (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:123:286)


I also tried using
jsons/cities.json
but that throws this error:

Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https, chrome-extension-resource.


Making a get request to an external resource works fine, but whenever I do it locally things just doesn't seem to work.

The JSON file I'm trying to get looks like this:

{"cities": {

{
city: "Stockholm",
latitud: "59",
longitud: "18",
id: "sthlm"
},
{
city: "Göteborg",
latitud: "58",
longitud: "12",
id: "gbg"
},
{
city: "Malmö",
latitud: "55",
longitud: "13",
id: "malmo"
},
{
city: "Umeå",
latitud: "63",
longitud: "20",
id: "umea"
}
}
}

Answer

On your local file you're getting a JSON parsing exception because your JSON is severely malformed. Try this format instead:

{
    "cities": [
        {
            "city": "Stockholm",
            "latitud": "59",
            "longitud": "18",
            "id": "sthlm"
        }
    ]
}
Comments