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

如何在Python中将多个JSON文件加载为对应数量的字典

解决JSON文件转Python字典并在函数中使用的方案

1. 核心思路

Python内置的json模块可以直接解析JSON文件(支持嵌套/非嵌套结构)并转换为字典。我们可以先实现一个通用的JSON读取函数,加载三个目标文件后,再编写业务逻辑函数来使用这些字典。

2. 代码实现

2.1 通用JSON读取函数

写一个复用性高的读取函数,处理文件不存在、格式错误等异常:

import json

def load_json_to_dict(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            return json.load(f)
    except FileNotFoundError:
        print(f"Error: 文件 {file_path} 不存在")
        return None
    except json.JSONDecodeError:
        print(f"Error: {file_path} 不是有效的JSON格式")
        return None

2.2 加载三个JSON文件

调用上述函数,将三个文件转换为字典:

# 加载目标文件(注意你写的file.1json应为file1.json,这里修正为常规命名)
dict_from_file1 = load_json_to_dict("file1.json")
dict_from_file2 = load_json_to_dict("file2.json")
dict_from_file3 = load_json_to_dict("file3.json")

# 校验所有字典加载成功
if not all([dict_from_file1, dict_from_file2, dict_from_file3]):
    exit("部分文件加载失败,程序终止")

2.3 在函数中使用字典

根据业务需求编写逻辑函数,以下是示例场景:

def process_json_dicts(d1, d2, d3):
    # 示例1:合并三个字典(键重复时后面的字典会覆盖前面的,可按需调整)
    combined_dict = {**d1, **d2, **d3}
    print("合并后的字典:", combined_dict)

    # 示例2:统计三个字典的总键数量
    total_key_count = len(d1) + len(d2) + len(d3)
    print(f"三个字典总键数:{total_key_count}")

    # 示例3:安全读取嵌套结构的值(避免KeyError)
    user_name = d1.get("user", {}).get("name", "未找到用户名")
    print(f"提取的用户名:{user_name}")

# 执行逻辑函数
process_json_dicts(dict_from_file1, dict_from_file2, dict_from_file3)

3. 注意事项

  • 若JSON文件与脚本不在同一目录,需传入绝对路径
  • 处理嵌套结构时,推荐用dict.get(key, 默认值)的方式安全取值,避免报错
  • 如果JSON文件编码不是UTF-8,需在open函数中指定对应编码(如encoding='gbk')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 03:48:10