Reputation: 135
How can I extract data from a JSON file? This is not my URL, it is an owned by an external source (ABS, is a company which produces weather information). This weather data has been put in a JSON File. Why cant I access its information? and store it
<html>
<head>
<meta content="text/html; charset = ISO-8859-1" http-equiv="content-type">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="application/javascript">
function loadJSON() {
var data_file = "http://reg.bom.gov.au/fwo/IDW60901/IDW60901.94610.json";
var http_request = new XMLHttpRequest();
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
document.getElementById("name").innerHTML = jsonObj.name;
document.getElementById("air_temp").innerHTML = jsonObj.air_temp;
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
</script>
<title>The Current Weather</title>
</head>
<body>
<h1>Weather in Perth City</h1>
<div class="central">
<button type="button" onclick="loadJSON()">Show Information </button>
</div>
</body>
</html>
Upvotes: 0
Views: 116
Reputation: 4005
You can send Cross origin requests using some sites like:
https://cors-anywhere.herokuapp.com/<url>
<html>
<head>
<meta content="text/html; charset = ISO-8859-1" http-equiv="content-type">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="application/javascript">
function loadJSON() {
var data_file = "https://cors-anywhere.herokuapp.com/http://reg.bom.gov.au/fwo/IDW60901/IDW60901.94610.json";
var http_request = new XMLHttpRequest();
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
document.getElementById("name").innerHTML = jsonObj.observations.data[0].name;
document.getElementById("air_temp").innerHTML = jsonObj.observations.data[0].air_temp;
}
}
http_request.open("GET", data_file, true);
http_request.setRequestHeader("X-Requested-With","XMLHttpRequest");
http_request.send();
}
</script>
<title>The Current Weather</title>
</head>
<body>
<h1>Weather in Perth City</h1>
<div class="central">
<button type="button" onclick="loadJSON()">Show Information </button>
</div>
<div id ="name"></div>
<div id="air_temp"></div>
</body>
</html>
Upvotes: 1