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

如何在Python中编写异常处理,处理JSON文件键值缺失的情况?

Handling Missing JSON Fields Without Deleting Entries

Hey there! I see you're working with a JSON file where some entries are missing 'name' or 'city' fields, and you want to keep those entries instead of discarding them. Let's fix this with proper error handling and default value filling.

Option 1: Explicit Exception Handling (try-except)

If you prefer to use explicit exception handling to catch missing keys, you can wrap each field access in its own try-except block. This way, even if one field is missing, the others will still be processed normally:

import json

save_list = []
json_path = '../business.json'

# Use a context manager to safely open the file
with open(json_path, 'r') as f:
    for line in f:
        save_dict = {}
        item = json.loads(line)
        
        # Handle 'name' field with default value if missing
        try:
            save_dict['name'] = item['name']
        except KeyError:
            save_dict['name'] = 'Unknown Name'  # Replace with your desired default
        
        # Handle 'neighborhood' field
        try:
            save_dict['neighborhood'] = item['neighborhood']
        except KeyError:
            save_dict['neighborhood'] = 'Unknown Neighborhood'
        
        # Handle 'city' field
        try:
            save_dict['city'] = item['city']
        except KeyError:
            save_dict['city'] = 'Unknown City'
        
        save_list.append(save_dict)

This approach makes it clear exactly where you're handling missing fields, and you can customize the default value for each field individually.

Option 2: Use Dictionary's get() Method (Simpler Approach)

A more concise way to achieve the same result is using Python's dictionary get() method. This method returns the value for a key if it exists, otherwise returns a specified default value—no exception handling required:

import json

save_list = []
json_path = '../business.json'

with open(json_path, 'r') as f:
    for line in f:
        item = json.loads(line)
        # Use get() to fetch fields with defaults
        save_dict = {
            'name': item.get('name', 'Unknown Name'),
            'neighborhood': item.get('neighborhood', 'Unknown Neighborhood'),
            'city': item.get('city', 'Unknown City')
        }
        save_list.append(save_dict)

This method is cleaner and reduces boilerplate code while still preserving all entries and filling missing fields with your chosen defaults.

Both approaches will keep all your data intact, even when fields are missing—pick the one that fits your coding style best!

内容的提问来源于stack exchange,提问作者HAO CHEN

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:12:05