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

如何用Python批量删除JSON文件中指定键的内容?

批量清理JSON中指定键的解决方案

问题背景

我有一个大型JSON文件,需要删除其中键为"owner"、"ticker"、"comment"和"ptr_link"的内容。该JSON文件结构中,"transactions"下的键为0至60的数字,每个键对应包含若干字典的列表,无法通过指定具体索引处理。现有代码仅能处理单个元素,需要实现批量处理的方法。

JSON示例

{
  "transactions": {
        "0": [
            {
                "transaction_date": "11/29/2022",
                "owner": "Spouse",
                "ticker": "<a href=\"https://finance.yahoo.com/q?s=WIW\" target=\"_blank\">WIW</a>",
                "asset_description": "Western Asset Inflation-Linked Opportunities &amp; Inc",
                "asset_type": "Stock",
                "type": "Sale (Full)",
                "amount": "$1,001 - $15,000",
                "comment": "--",
                "ptr_link": "https://efdsearch.senate.gov/search/view/ptr/5ac4d053-0258-4531-af39-8a8067f0d085/"
            },
            {
                "transaction_date": "11/29/2022",
                "owner": "Spouse",
                "ticker": "<a href=\"https://finance.yahoo.com/q?s=GBIL\" target=\"_blank\">GBIL</a>",
                "asset_description": "Goldman Sachs Access Treasury 0-1 Year ETF",
                "asset_type": "Other Securities",
                "type": "Purchase",
                "amount": "$1,001 - $15,000",
                "comment": "--",
                "ptr_link": "https://efdsearch.senate.gov/search/view/ptr/5ac4d053-0258-4531-af39-8a8067f0d085/"
            }
          ]
     }
}

现有代码(仅处理单个元素)

import json


data = json.load(open("xxxtester.json"))

data1 = data['transactions']
data2 = data1['0'][0]

for i in data2:
    del data2['owner']
for i in data2:
    del data2['ticker']
for i in data2:
    del data2['comment']
for i in data2:
    del data2['ptr_link']


open("xxxtester.json", "w").write(json.dumps(data, indent=4))

批量处理解决方案

改进后代码

import json

# 统一定义要删除的键,方便后续维护
keys_to_remove = ["owner", "ticker", "comment", "ptr_link"]

# 用with语句自动管理文件资源,避免手动关闭的麻烦
with open("xxxtester.json", "r") as f:
    data = json.load(f)

# 遍历transactions下的所有数字键(如"0"、"1"直到"60")
for trans_key in data["transactions"]:
    # 遍历当前键对应的所有交易字典
    for trans_item in data["transactions"][trans_key]:
        # 逐个删除指定键,pop的第二个参数避免键不存在时报错
        for key in keys_to_remove:
            trans_item.pop(key, None)

# 将处理后的数据写回文件
with open("xxxtester.json", "w") as f:
    json.dump(data, f, indent=4)

代码说明

  • 使用with操作文件,无需手动关闭,安全且简洁
  • 把要删除的键集中到列表,后续修改只需调整列表内容,维护成本更低
  • 两层循环覆盖所有数据:外层遍历transactions下的所有数字键,内层遍历每个键对应的交易列表中的字典
  • 用dict.pop(key, None)替代直接del,即使某个字典没有目标键也不会抛出异常
  • 自动批量处理所有符合结构的元素,不用指定具体索引

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 18:30:15