1

I am trying to get the JSON data using the $http function; I am always getting error for this. Here is my HTML code:

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="customersCtrl"> 

<ul>
   <li ng-repeat="x in code">
     {{ x.code }}
   </li>
</ul>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
   $http.get("data.json")
   .success(function (response) {$scope.code = response;})
   .error(function (response) {alert("Error")})
});
</script>

</body>
</html>

Here is my data.json file:

{
  "code":"#include <stdio.h>

          int main()
          {
             printf('Hello world');
             return 0;
          }"
}

Here is the plunker http://plnkr.co/edit/Q4dsCjHM3ykgp2SaHw35?p=preview

1
  • your data is not a proper json Commented Aug 10, 2015 at 13:27

3 Answers 3

2

Do change your data to below.Basically it should be string, use pre tag for line break & then replace enter by \n

{
  "code": "#include <stdio.h>\n int main()\n printf('Hello world');\n return 0;\n}"
}

HTML

<ul>
  <li ng-repeat="x in code">
    <pre>{{ x }}</pre>
  </li>
</ul>

Working Plunkr

Sign up to request clarification or add additional context in comments.

3 Comments

How can I include line breaks can u help me
Where should I include the pre tag . Can i include in json file.
@RamanaUday it should be html check my html in answer, it should be inside li tag <pre>{{ x }}</pre>
2

Your JSON is poorly formatted. The string line of code should be on one line e.g.,

{
    "code": "#include <stdio.h> int main() ...."
}

You can always validate your JSON at jsonlint.com

Comments

0

Your JSON is not well formated.

JSON

{
  "code":"#include <stdio.h>int main(){printf('Hello world');return 0;}"
}

Then, you can access to the code field in your request :

Controller

$http.get("data.json")
  .success(function (response) {
    $scope.code = response.code;
})
.error(function (response) {
    alert("Error");
});

3 Comments

why you need response.data?
Why ? Yes no need of response.data, just saying response.code to retrieve the data of the field code into the JSON
because you already have data in your first option..if you used .then then only you will need to say reponse.data, though response.code is correct.I'm removing my downvote. Thanks :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.