Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS JSON parse(ajax)

I have been tring to make a ajax request but there seems to be a problem. When my json attributes names are in " ( like {"name":value"} ), it works but when attribute names are not. I have following excepiton

SyntaxError: Unexpected token s
at Object.parse (native)
at pb (http://localhost:8080/angularjs/lib/angular.min.js:12:472)
at Vc.d.defaults.transformResponse (http://localhost:8080/angularjs/lib/angular.min.js:92:314)
at http://localhost:8080/angularjs/lib/angular.min.js:92:127
at Array.forEach (native)
at n (http://localhost:8080/angularjs/lib/angular.min.js:6:192)
at Qb (http://localhost:8080/angularjs/lib/angular.min.js:92:109)
at c (http://localhost:8080/angularjs/lib/angular.min.js:93:295)
at h (http://localhost:8080/angularjs/lib/angular.min.js:77:437)
at http://localhost:8080/angularjs/lib/angular.min.js:78:169 

Here is my code:

index.html:

<!doctype html>
<html ng-app>
<head>
<script src="lib/angular.min.js"></script>
<script src="js/indexApp.js"></script>
</head>
<body>
    <div>
        <div ng-controller="AjaxController">
            {{users.data}}
        </div>
    </div>
</body>
</html>

indexApp.js

function AjaxController($scope, $http) {
$scope.beers = [ 0, 1, 2, 3, 4, 5, 6 ];
console.log("OMW");
$http({
    method : 'GET',
    url : 'data.json'
}).success(function(data, status, headers, config) {
    $scope.users = data;
}).error(function(data, status, headers, config) {
    $scope.users = "error" + data;
});

};

data.json

{
    success : "true",
    data: [{name:"val"}]
}
like image 536
mcadirci Avatar asked Apr 12 '13 13:04

mcadirci


2 Answers

You must wrap attribute names in ". This is the only way to specify valid transport JSON, which is stricter than object notation in an executable JavaScript context. Any JSON parser will fail if you try to use the more lax notation.

See also the spec for JSON which mandates this.

like image 123
Ezekiel Victor Avatar answered Oct 03 '22 21:10

Ezekiel Victor


Even I had the similar issue and the solution is, your string data should be in a specific format for JSON.parse or angular.fromJson to work.

For ex:

var myString = '{"name":"nomad"}';
console.log(JSON.parse(myString));

The console output is: Object {name: "nomad"}

like image 38
nomad Avatar answered Oct 03 '22 22:10

nomad