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

Python JSON解析脚本报错排查:TextIOWrapper不可序列化

问题分析与修复方案

嘿,我一眼就看到你代码里的问题啦——这个报错的核心是你搞混了json模块函数的用法,还有文件读取的方式不对。

错误根源

你写的这行代码:

data = json.dumps(open(jsonDirectory + filename))

有两个关键错误:

  1. open()返回的是文件句柄(TextIOWrapper对象),不是文件里的JSON内容,直接把它传给json.dumps()肯定会报错——dumps的作用是把Python对象转换成JSON字符串,而不是读取并解析JSON文件。
  2. 要读取JSON文件并转成Python字典/列表,你应该用json.load(),而不是dumps。

另外还有两个小细节可以优化,让代码更健壮、更符合Python风格:

  • 用with语句处理文件,它会自动帮你关闭文件,避免资源泄漏。
  • 遍历Records列表时,不用range(len(data["Records"])),直接遍历元素+enumerate()获取索引更简洁。

修正后的代码

import json
import os
from pprint import pprint

jsonDirectory = "/path/to/dir/"
targetRegion = "-insert-region-here"

print("Searching for records with AWS Region: " + targetRegion)
print("")

for filename in os.listdir(jsonDirectory):
    # 跳过非JSON文件,避免无关文件干扰(可选但推荐)
    if not filename.endswith(".json"):
        continue
    print("Reading: " + filename)
    # 使用with语句安全读取文件,并用json.load解析JSON内容为Python对象
    with open(os.path.join(jsonDirectory, filename), 'r') as f:
        data = json.load(f)
    # 直接遍历Records列表,用enumerate同时获取索引和记录
    for idx, record in enumerate(data["Records"]):
        if record["awsRegion"] == targetRegion:
            print("---------------------------")
            print(f"Record #{idx}")
            print(f"Username: {record['userIdentity']['userName']}")
            print(f"Event name: {record['eventName']}")
            print(f"Event time: {record['eventTime']}")
            print("---------------------------")
    print("")

print("Completed reading files.")

额外优化说明

  • 新增了filename.endswith(".json")的判断,过滤目录里的非JSON文件,防止脚本读取无效内容。
  • 用os.path.join()拼接路径,比直接用+更安全,能自动适配Windows/macOS/Linux的路径分隔符。
  • 用f-string替代字符串拼接,代码更简洁易读。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:40:32