I am trying to loop through my JSON array and get a random value from it.
Here is my Json Code:
{"cities":[{"city":"St.John","xCoor":931,"yCoor":349},{"city":"Halifax","xCoor":844,"yCoor":424},{"city":"Charlottetown","xCoor":838,"yCoor":407},{"city":"Fredericton","xCoor":800,"yCoor":422},{"city":"Quebec","xCoor":734,"yCoor":427},{"city":"Ottawa","xCoor":685,"yCoor":459},{"city":"Toronto","xCoor":655,"yCoor":483},{"city":"Winnipeg","xCoor":420,"yCoor":430},{"city":"Regina","xCoor":336,"yCoor":417},{"city":"Edmonton","xCoor":250,"yCoor":364},{"city":"Victoria","xCoor":111,"yCoor":398},{"city":"Whitehorse","xCoor":115,"yCoor":235},{"city":"Yellowknife","xCoor":285,"yCoor":271},{"city":"Iqaluit","xCoor":645,"yCoor":243}]}
In this case I want to loop through the "Cities" array and get a random "city".
This is my code to get the Json Data:
function getJsonData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState==4 && xhttp.status==200) {
schedule = JSON.parse(xhttp.responseText);
}
}
xhttp.open("GET", "capitals.json", true);
xhttp.send();}
This is what I have written to try and get the a Random City from the Cities array:
function drawPlanes() {
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
var cityNames = schedule["cities"];
for(var i = 0; i < cityNames.length; i++) {
var obj = cityNames[i];
var randomCity = obj.city[Math.floor(Math.random()*obj.city)];
console.log(randomCity);
}}
In summary, I essentially just want to loop through this Json Array and get a Random City Value, for example: in the console it just prints lets say "Quebec", but the problem here is that what I wrote is not working. Hopefully what I am asking is clear enough.