1

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);

});
halfer
  • 19,824
  • 17
  • 99
  • 186
J86
  • 14,345
  • 47
  • 130
  • 228
  • Have you put a break point on that object in the controller to see if that's the correct object being returned? I'm not seeing any issues with your JSON. – Christopher Marshall Feb 04 '14 at 20:51
  • I tried your JSON on a demo app with angular an it works just fine. – Dalorzo Feb 04 '14 at 20:59
  • added controller code. – J86 Feb 04 '14 at 20:59
  • @Dalorzo seriously? How did you consume the json in the view? – J86 Feb 04 '14 at 21:00
  • So I've tried passing this directly to JSON.parse in both Firefox and Chrome, and it also says the JSON is invalid. I'm not sure why JSONLint says it's valid, but it doesn't pass in a browser. – Jeff Hubbard Feb 04 '14 at 21:00
  • Thanks @JeffHubbard, so it isn't just me :( – J86 Feb 04 '14 at 21:01
  • @Jeff Hubbard Bare in mind that if you just copy paste the data and quote it in single quotes it won't work. You would need to also replace all \ with \\ to properly encode a backslash! – user2847643 Feb 04 '14 at 22:08
  • Good catch. I didn't see any \ on a quick glance, but with that change it does pass JSON.parse. So then that's the problem, Ciwan. – Jeff Hubbard Feb 04 '14 at 22:12

2 Answers2

2

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.

Community
  • 1
  • 1
user2847643
  • 2,893
  • 14
  • 22
0

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