3

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
  • Where do you see the error message "malformed"? Commented Apr 10, 2013 at 1:07

1 Answer 1

1
<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>
Sign up to request clarification or add additional context in comments.

1 Comment

For some reason, I could not accept your answer or leave a comment for 9 min.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.