Reputation: 207
Using the following code, I am trying to read sample data from the link https://data.mo.gov/resource/hsus-bft8.json
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"></script>
</head>
<body>
<script>
$(document).ready(function(){
$.getJSON("https://data.mo.gov/resource/hsus-bft8.json", function(data){
document.write(data.licensee + "<br>");
document.write(data.street_number);
}).fail(function(){
document.write("An error has occurred.");
});
});
</script>
</body>
</html>
but it simply returns 2 undefined
fields. What am I missing here?
Upvotes: 1
Views: 62
Reputation: 688
An array is being returned. You need to loop on the complete array/ use index to print those properties. Try following code
<script>
$(document).ready(function(){
$.getJSON("https://data.mo.gov/resource/hsus-bft8.json", function(data){
data.forEach( elem => {
document.write(elem.licensee + "<br>");
document.write(elem.street_number);
});
}).fail(function(){
document.write("An error has occurred.");
});
});
</script>
Upvotes: 2
Reputation: 71
Here your missing the loop, because it is a array.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"></script>
</head>
<body>
<script>
$(document).ready(function(){
$.getJSON("https://data.mo.gov/resource/hsus-bft8.json", function(data){
var len = data.length;
for(var i=0;i<len;i++){
document.write(data[i].licensee + " : " );
document.write(data[i].street_number + "<br/><br/>");
}
}).fail(function(){
document.write("An error has occurred.");
});
});
</script>
</body>
</html>
Upvotes: 2