如何正确解析包含国家、州、城市的大型JSON文件?
Hey there! Parsing this country-state-city JSON is straightforward once you understand its nested structure. Let me walk you through how to do it in two of the most common languages—Python and JavaScript—with practical examples.
First, let's quickly map out the structure of your JSON to make sure we're on the same page:
- Top-level is a
Countriesarray - Each item in
Countriesis an object withCountryNameand anotherStatesarray - Each
Statesitem hasStateNameand aCitiesarray of strings
Parsing in Python
Python has a built-in json module that makes this super easy. You can work with either a JSON file or a raw JSON string.
Example 1: Reading from a JSON file
import json # Open and load the JSON file with open('your_file.json', 'r') as json_file: data = json.load(json_file) # Traverse the nested structure for country in data['Countries']: print(f"* Country: {country['CountryName']}") for state in country['States']: print(f" - State: {state['StateName']}") print(f" → Cities: {', '.join(state['Cities'])}")
Example 2: Parsing a raw JSON string
If you're working with the JSON content as a string (like the one you provided), use json.loads() instead:
import json # Your raw JSON string json_content = '''{ "Countries":[ { "CountryName":"India", "States":[ { "StateName":"Maharashtra", "Cities":[ "Pune", "Nagpur", "Mumbai" ] }, { "StateName":"Kerala", "Cities":[ "Kochi", "Munnar" ] } ] }, { "CountryName":"Australia", "States":[ { "StateName":"Aukland", "Cities":[ "GlenField", "Henderson", "MilFord" ] }, { "StateName":"Melbourne", "Cities":[ "Melbourne", "South Oakleigh" ] } ] } ] }''' # Parse the string into a Python dictionary data = json.loads(json_content) # Same traversal logic as above for country in data['Countries']: print(f"* Country: {country['CountryName']}") for state in country['States']: print(f" - State: {state['StateName']}") print(f" → Cities: {', '.join(state['Cities'])}")
Parsing in JavaScript
JavaScript also has native JSON parsing support with JSON.parse(). Here are examples for both Node.js (server-side) and browser environments.
Example 1: Node.js (reading from a file)
const fs = require('fs'); // Read the JSON file asynchronously fs.readFile('your_file.json', 'utf8', (error, jsonString) => { if (error) { console.log('Oops, error reading the file:', error); return; } try { // Parse the JSON string into a JavaScript object const data = JSON.parse(jsonString); // Traverse the structure data.Countries.forEach(country => { console.log(`* Country: ${country.CountryName}`); country.States.forEach(state => { console.log(` - State: ${state.StateName}`); console.log(` → Cities: ${state.Cities.join(', ')}`); }); }); } catch (parseError) { console.log('Error parsing JSON:', parseError); } });
Example 2: Browser environment (or raw string)
// Your raw JSON string const jsonString = `{ "Countries":[ { "CountryName":"India", "States":[ { "StateName":"Maharashtra", "Cities":[ "Pune", "Nagpur", "Mumbai" ] }, { "StateName":"Kerala", "Cities":[ "Kochi", "Munnar" ] } ] }, { "CountryName":"Australia", "States":[ { "StateName":"Aukland", "Cities":[ "GlenField", "Henderson", "MilFord" ] }, { "StateName":"Melbourne", "Cities":[ "Melbourne", "South Oakleigh" ] } ] } ] }`; try { const data = JSON.parse(jsonString); // Traverse and log the data data.Countries.forEach(country => { console.log(`* Country: ${country.CountryName}`); country.States.forEach(state => { console.log(` - State: ${state.StateName}`); console.log(` → Cities: ${state.Cities.join(', ')}`); }); }); } catch (error) { console.error('Failed to parse JSON:', error); }
Quick Tips for Large JSON Files
If your JSON file is really large (like gigabytes), loading the entire thing into memory might cause issues:
- In Python, use libraries like
ijsonfor streaming parsing - In Node.js, use the
streammodule to read and parse the file in chunks
内容的提问来源于stack exchange,提问作者Danish Ajaib

