PyMongo中BSON转Dict失败,报TypeError错误求解决
解决BSON转JSON时的TypeError问题
错误原因
你当前使用的bson.decode()函数仅适用于解码单个BSON文档的字节流。如果你的BSON文件包含多个文档(比如MongoDB导出的批量数据),直接调用该函数会触发解析逻辑错误,抛出TypeError: 'str' object cannot be interpreted as an integer。
修复步骤
1. 改用多文档解码函数
将代码中的bson.decode()替换为bson.decode_all(),这个函数专门用于处理包含多个BSON文档的字节数据,返回一个字典列表:
# 替换原解码行 data = bson.decode_all(fcache.read(), codec_options=bson_codec_options)
2. 完整转换为JSON(可选)
如果需要将解析后的结果保存为JSON文件,需要处理BSON中的Python特定类型(如datetime),可以自定义JSON编码器:
import json from datetime import datetime class BSONJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime): return obj.isoformat() # 其他特殊类型可在此扩展处理逻辑 return super().default(obj) # 在循环中添加JSON转换和保存逻辑 for file in bson_files: file_path = os.path.join(current_dir, file) with open(file_path, 'rb') as fcache: data = bson.decode_all(fcache.read(), codec_options=bson_codec_options) # 转换为格式化的JSON字符串 json_str = json.dumps(data, cls=BSONJSONEncoder, indent=2, ensure_ascii=False) # 保存为同名JSON文件 json_file_path = os.path.splitext(file_path)[0] + '.json' with open(json_file_path, 'w', encoding='utf-8') as f: f.write(json_str) print(f"已转换文件: {json_file_path}")
3. 单个文档的特殊处理
如果确认你的BSON文件仅包含单个文档,仍出现该错误,需要检查:
- 文件是否损坏:使用MongoDB官方工具
bsondump验证文件有效性(命令:bsondump your_file.bson) - 读取的字节流是否完整:打印
len(fcache.read())确认不为0,避免读取空文件
内容的提问来源于stack exchange,提问作者Griffith
相关产品推荐
相关产品推荐

