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

如何用Python删除JSON顶层键并保留对应值?

移除JSON顶层特定键并保留其值的实现方案

针对你需要批量处理大型JSON文件,移除Students数组元素中顶层的邮箱格式键(如firstname.lastname@mail.com)并保留其对应值的需求,这里提供两种高效的实现方案:

方案一:使用标准库json(适合中等大小文件)

如果文件大小在内存可承受范围内,用Python内置json模块就能快速处理:

import json

def process_json_file(input_path, output_path):
    with open(input_path, 'r', encoding='utf-8') as f:
        data = json.load(f)
    
    # 遍历Students数组,把每个元素替换为邮箱键对应的值
    data['Students'] = [
        next(iter(student.values()))  # 取元素中唯一键对应的值
        for student in data['Students']
    ]
    
    with open(output_path, 'w', encoding='utf-8') as f:
        json.dump(data, f, indent=4)

# 调用示例
process_json_file('input.json', 'output.json')

方案二:流式处理(适合超大型JSON文件)

如果文件体积过大,无法一次性加载到内存,推荐用ijson库做流式解析,避免内存溢出:

  1. 先安装依赖:
pip install ijson
  1. 流式处理代码:
import ijson
import json

def stream_process_json(input_path, output_path):
    with open(input_path, 'rb') as infile, open(output_path, 'w', encoding='utf-8') as outfile:
        # 写入JSON开头结构
        outfile.write('{"Students": [')
        first_item = True
        
        # 流式读取Students数组里的每个元素
        for student in ijson.items(infile, 'Students.item'):
            # 提取邮箱键对应的值
            cleaned_student = next(iter(student.values()))
            
            # 处理数组元素的逗号分隔
            if not first_item:
                outfile.write(',')
            first_item = False
            
            # 写入清理后的元素
            json.dump(cleaned_student, outfile, indent=4)
        
        # 写入JSON结尾结构
        outfile.write(']}')

# 调用示例
stream_process_json('large_input.json', 'large_output.json')

补充说明

  • 两种方案默认每个Students数组元素中只有一个顶层邮箱格式键,直接取其对应值即可。
  • 批量处理多个文件时,只需遍历文件路径列表,循环调用上述函数即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 17:33:26