SyntaxError: Unexpected token o at Object.parse (native) AngularJS
Asked Answered
G

5

31

Question from AngularJS noob.

I am trying to use an asmx web service to display grid. I tested the web service and it correctly outputs the JSON data. Here is my controller

app.controller('SetupController', ['$scope', '$http', function ($scope, $http) {

    var url = 'app/pricefilessetup/grid.asmx/getGridJson';

    $http.get(url).success(function (data) {
        var myjson = JSON.parse(data);
        $scope.products= JSON.parse(myjson);
    });
}]);

For some reason, SO is not allowing me to paste the html but it basically has a ng-controller directive and ng-repeat to loop through the JSON data.

When I run this web app, I get the error

SyntaxError: Unexpected token o at Object.parse (native) and it points to following line

  $scope.questions = JSON.parse(myjson);

I tried checking the value of myjson using alert and it displays [object Object], [object Object], ...

Is there anything I am missing here

Grimona answered 21/4, 2015 at 5:19 Comment(2)
I doubt you need to ever use JSON.parse. Angular expects the response to be JSON by default and deserialises it for you.Goer
Also, alert is a terrible debugging tool. Use console.log instead (or Angular's $log service)Goer
B
29

I think data returned is already in JSON, no need of JSON.parse(), unless it in string format.

$scope.products= data;
Blasphemous answered 21/4, 2015 at 5:25 Comment(0)
W
8

Why you using JSON.parse in two times?

 var myjson = JSON.parse(data);
  $scope.products = JSON.parse(myjson);

You have already parse the data object,So then why you parsing another one time?

also i think your data is return Json result, so you don't need to parse the object

just use this

$scope.products = data;
Wellheeled answered 21/4, 2015 at 5:36 Comment(0)
G
7

Your variable myjson is already a valid JavaScript Object. You do not have to use JSON.parse on it.

Gruelling answered 21/4, 2015 at 5:22 Comment(0)
C
0

Simple solution, just use an absolute url:

var url = 'http://demo/app/pricefilessetup/grid.asmx/getGridJson';

Instead of using var url = 'app/pricefilessetup/grid.asmx/getGridJson'; I have checked.

Callison answered 8/3, 2016 at 19:7 Comment(0)
I
0

In my case it was string literal being passed in as parameter to JSON.parse().

For Example JSON.parse('asdf') would throw an error Uncaught SyntaxError: Unexpected token a.

With specific case, in Single page angular application, the access token was being passed to the JSON.parse() and clearing the cookies in browser solved the problem for me.

Intemerate answered 1/4, 2016 at 21:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.