Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

malformed JSON while JSON is valid?

Tags:

json

jquery

ajax

I am trying to get a JSON object from an external file, but I always get the error: malformed , that points to the first { of my JSON file. I tested my JSON file on this website: http://jsonlint.com/ and it is valid.

This is my JSON code:

{
  "employees": [{
      "firstName": "John",
      "lastName": "Doe"
    }, {
      "firstName": "Anna",
      "lastName": "Smith"
    }, {
      "firstName": "Peter",
      "lastName": "Jones"
    }
  ]
}

And this is my script:

$.getJSON("employe.json", function (data) {
  document.write(data.employees[0].firstName);
});

What am I doing wrong?


1 Answers

<script>
 $(document).ready(function() {
    $.getJSON("employe.json", function(data) {
    document.write(data.employees[0].firstName);
    });
 });
</script>

Or instead of document write

 alert( data.employees[0].firstName);

Odds are you are going to want $.each iteration

 <script>
 $(document).ready(function() {
    $.getJSON("employe.json", function(data) {
      $.each(data.employees, function(arrayID, employee) {
            alert(employee.firstName);
      });
    });
 });
</script>
like image 83
Jay Rizzi Avatar answered Mar 31 '26 09:03

Jay Rizzi