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

如何用Python根据日期值中的年份删除指定JSON对象?

问题解决:保留2022年及以后的交易记录

需求说明

有一个存储交易数据的JSON文件,结构中transactions下包含多个键值对,值为交易对象列表,每个交易对象含transaction_date字段(格式如MM/DD/YYYY)。需要删除所有日期在2022年之前的交易对象,仅保留2022年及以后的记录。原代码逻辑错误,无法正确识别日期中的年份,需修改实现需求。

示例输入JSON

{
    "transactions": {
        "0": [
            {
                "transaction_date": "11/29/2022",
                "asset_description": "Western Asset Inflation-Linked Opportunities & Inc",
                "asset_type": "Stock",
                "type": "Sale (Full)",
                "amount": "$1,001 - $15,000",
                "party": "Democrat"
            },
            {
                "transaction_date": "11/29/2021",
                "asset_description": "Goldman Sachs Access Treasury 0-1 Year ETF",
                "asset_type": "Other Securities",
                "type": "Purchase",
                "amount": "$1,001 - $15,000",
                "party": "Democrat"
            }
          ],
        "1":[
            {
                "transaction_date": "11/29/2019",
                "asset_description": "Western Asset Inflation-Linked Opportunities & Inc",
                "asset_type": "Stock",
                "type": "Sale (Full)",
                "amount": "$1,001 - $15,000",
                "party": "Democrat"
            }
          ]
    }
  }

修改后的Python代码

import json

# 读取JSON文件
with open("xxxtester.json", "r") as f:
    data = json.load(f)

# 遍历transactions中的每个键值对
transactions = data["transactions"]
keys_to_delete = []

for key, transaction_list in transactions.items():
    # 筛选出2022年及以后的交易对象
    filtered_transactions = [
        tx for tx in transaction_list
        if int(tx["transaction_date"].split("/")[-1]) >= 2022
    ]
    if filtered_transactions:
        transactions[key] = filtered_transactions
    else:
        # 若筛选后列表为空,标记该键待删除
        keys_to_delete.append(key)

# 删除空列表对应的键
for key in keys_to_delete:
    del transactions[key]

# 写入修改后的JSON文件
with open("xxxtester.json", "w") as f:
    json.dump(data, f, indent=4)

代码关键说明

  • 使用with语句读写文件,确保文件正确关闭
  • 对每个交易对象,通过split("/")[-1]提取日期字符串中的年份部分,转为整数后判断是否≥2022
  • 用列表推导式高效筛选符合条件的交易
  • 处理后若某个交易列表为空,则删除对应的键(如示例中的"1"键)
  • 最后用json.dump格式化输出JSON,保持缩进可读性

期望输出JSON

{
    "transactions": {
        "0": [
            {
                "transaction_date": "11/29/2022",
                "asset_description": "Western Asset Inflation-Linked Opportunities & Inc",
                "asset_type": "Stock",
                "type": "Sale (Full)",
                "amount": "$1,001 - $15,000",
                "party": "Democrat"
            }
        ]
    }
}

内容的提问来源于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.09 01:15:56