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?
<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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With