J86
J86

Reputation: 15237

I am receiving a JSON.parse error on valid JSON

I am parsing some JSON. My JSON is valid, because when I run it through JSONLint, I get the green label saying Valid JSON, yet for some reason I still cannot parse the JSON via my Angular Controller.

JSON code can be found here.

Controller Code:

savvyApp.controller('ProductsCtrl', function($scope) {

    var apiJSONResult = '<linked json here>';   

    $scope.apiResult = JSON.parse(apiJSONResult);

});

Upvotes: 1

Views: 10567

Answers (2)

Richnologies
Richnologies

Reputation: 66

Try to use the angular fromJson method instead:

savvyApp.controller('ProductsCtrl', function($scope) {

    var apiJSONResult = '<linked json here>';   

    $scope.apiResult = angular.fromJson(apiJSONResult);

});

I also leave you here the Angular documentation link of the method

https://docs.angularjs.org/api/ng/function/angular.fromJson

Upvotes: 0

user2847643
user2847643

Reputation: 2935

JSON.parse string with quotes

That should be the answer. In short you cannot just copy paste JSON and quote it in single quotes and expect it to work. You would also need to make sure the backslashes are encoded.

So the JSON is in fact valid. But it is no longer valid if you copy paste it into a js file. It has to do with how javascript encodes backslashes in strings.

Upvotes: 2

Related Questions