Created
August 11, 2023 07:00
-
-
Save hzw1199/f8dc318116bd2ed35c536b57a71867a3 to your computer and use it in GitHub Desktop.
Convert BSON to JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 导入所需的库 | |
import bson | |
import json | |
import datetime | |
# 定义一个类,继承自json库的JSONEncoder类 | |
class BSONEncoder(json.JSONEncoder): | |
# 重写default方法,用来处理BSON中的datetime对象 | |
def default(self, obj): | |
# 如果对象是datetime类型,就返回它的年月日字符串 | |
if isinstance(obj, datetime.datetime): | |
return obj.strftime("%Y-%m-%d %H:%M:%S") | |
# 否则,就调用父类的default方法 | |
else: | |
return super().default(obj) | |
# 定义一个函数,用来将BSON文件转换成JSON文件 | |
def convert_bson_to_json(bson_file, json_file): | |
# 打开BSON文件,并读取所有的条目 | |
with open(bson_file, "rb") as f: | |
bson_data = bson.decode_all(f.read()) | |
# 创建一个空列表,用来存储转换后的JSON条目 | |
json_data = [] | |
# 遍历每个BSON条目 | |
for item in bson_data: | |
# 使用自定义的编码器和json.loads方法,将每个条目转换成Python对象 | |
item_dict = json.loads(json.dumps(item, cls=BSONEncoder)) | |
# 将每个对象添加到JSON列表中 | |
json_data.append(item_dict) | |
# 打开JSON文件,并直接写入JSON列表 | |
with open(json_file, "w") as f: | |
json.dump(json_data, f, indent=4) | |
# 打印成功信息 | |
print(f"Successfully converted {bson_file} to {json_file}") | |
# 如果这个文件是作为主程序运行,就获取命令行参数,并调用转换函数 | |
if __name__ == "__main__": | |
import sys | |
# 检查参数个数是否正确 | |
if len(sys.argv) != 3: | |
print("Usage: python convert_bson_to_json.py <bson_file> <json_file>") | |
sys.exit(1) | |
# 获取参数值 | |
bson_file = sys.argv[1] | |
json_file = sys.argv[2] | |
# 调用转换函数 | |
convert_bson_to_json(bson_file, json_file) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment