You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何正确解析包含国家、州、城市的大型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 Countries array
  • Each item in Countries is an object with CountryName and another States array
  • Each States item has StateName and a Cities array 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 ijson for streaming parsing
  • In Node.js, use the stream module to read and parse the file in chunks

内容的提问来源于stack exchange,提问作者Danish Ajaib

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:21:15