Load the JSON string from the file world-cities.json into the
string citiesJSON like this:
const fs = require("fs");
fs.readFile('world-cities.json', (err, data) => {
if (err) {
console.log("Error reading file " +
"world-cities.json");
}
else {
var citiesJSON = JSON.parse(data);
// Add your own code here
// to obtain the answers for
// exercises 6a, 6b, and 6c.
}
});
This JSON file contains data for all cities in the world with population 10,000 persons or more.
Now convert this string to the array of objects cities and answer these questions:
- List all cities in the subcountry Wyoming of the country United States.
(Wyoming is the state with fewest cities with population over 10,000, so the
answer is easy to check.
- List the country and subcountry of all cities named Springfield.
- How many cities are in the JSON file?
Answer: Here is the JavaScript code for parts 3a, b, and c:
// Part 3a. List all cities in Wyoming.
console.log("Cities in Wyoming");
for(var c of citiesJSON) {
if (c.country == "United States" &&
c.subcountry == "Wyoming") {
console.log(c.name);
}
}
// Part 3b. List the subcountry and country of
// all cities named Springfield.
console.log("\nCities named Springfield.")
for(var c of citiesJSON) {
if (c.name == "Springfield") {
console.log(c.subcountry + ", " +
c.country);
}
}
// Part 3c. Display the number of cities over 10,000 population.
console.log("\nCount of cities over 10,000 population");
console.log(citiesJSON.length);