如何解决TypeError: Commit类型对象无法JSON序列化的问题
解决JSON序列化Commit对象的TypeError问题
这个错误的核心原因是:Python标准库的json模块仅支持序列化内置数据类型(如dict、list、str、int等),而你的仓库信息字典中包含了Commit类的实例——这类自定义对象不在默认序列化范围内。
以下是几种实用的解决方法:
方法1:自定义序列化函数(最常用)
编写一个函数,将Commit实例转换为JSON可识别的字典,然后通过json.dumps的default参数传入该函数:
import json from git import Commit # 以gitpython库的Commit类为例 def serialize_commit(obj): if isinstance(obj, Commit): # 提取你需要的Commit关键信息,按需调整字段 return { 'commit_id': obj.hexsha, 'author': obj.author.name, 'author_email': obj.author.email, 'commit_message': obj.message.strip(), 'commit_time': obj.committed_datetime.isoformat() } # 非Commit对象抛出原错误 raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable") # 假设你的仓库信息字典是repo_data with open('repo_info.json', 'w') as f: json.dump(repo_data, f, default=serialize_commit, indent=2)
方法2:直接利用对象的__dict__属性(快速但可能冗余)
如果Commit类的属性都存储在__dict__中,可以直接返回这个字典,但会包含一些内部冗余数据:
def serialize_commit(obj): if isinstance(obj, Commit): return obj.__dict__ raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable")
方法3:用第三方序列化库(适合复杂场景)
如果项目中有大量自定义对象需要序列化,可以用marshmallow这类库定义规范的序列化Schema:
import json from marshmallow import Schema, fields from git import Commit class CommitSchema(Schema): commit_id = fields.Str(attribute='hexsha') author_name = fields.Str(attribute='author.name') author_email = fields.Str(attribute='author.email') commit_message = fields.Str() commit_time = fields.DateTime(attribute='committed_datetime') # 处理字典中的Commit实例 schema = CommitSchema() if 'commits' in repo_data: repo_data['commits'] = [schema.dump(commit) for commit in repo_data['commits']] # 写入JSON文件 with open('repo_info.json', 'w') as f: json.dump(repo_data, f, indent=2)
内容的提问来源于stack exchange,提问作者Gimbo
相关产品推荐
相关产品推荐

