Why does AngularJS "$http.get().then(...)" work on plain text files, but not JSON files?

1.3k views Asked by At

Here are two demos of using AngularJS "$http.get().then(...)". One reads plain text files, and the other reads JSON files.

read plain text vs read JSON

However, the first one works but the second doesn't. Everything else is the same, except for file1.txt, file2.txt, file3.txt, and line 23 of app.js.

  /* content of file: 100 */

  function getNumber(file) {
      return $http.get(file).then(function(response){
         return parseInt(response.data, 10);
      });
  }

vs

  /* content of file: [{'n':100}] */

  function getNumber(file) {
      return $http.get(file).then(function(response){
         return response[0].n;
      });
  }

I followed this post by trying to create a service but still got some errors.

Basically, how to make the second one work? Thanks in advance! It would be more explicit if you look at the demos.

1

There are 1 answers

0
Vincent F On BEST ANSWER

[{'n':100}] is not valid JSON. Change it to [{"n":100}]