我有一些 bson 文件(我没有它们来自的数据库,只有名为 file1.bson 和 file2.bson 的文件),我希望能够将它们翻译成 json。我的代码如下:
import json
import bson
to_convert = ["./file1", "./file2"]
for i in to_convert:
INPUTF = i + ".bson"
OUTPUTF = i + ".json"
input_file = open(INPUTF, 'r', encoding='utf-8')
output_file = open(OUTPUTF, 'w', encoding='utf-8')
reading = (input_file.read()).encode() #reading = (input_file.read()+'\0').encode()
datas = bson.BSON.decode(reading)
json.dump(datas, output_file)
它引发“bson.errors.InvalidBSON: bad eoo”,这似乎表明文件末尾的 NULL 字符丢失了,但即使我手动添加它(如评论部分),错误仍然存在。
我该如何解决这个问题?
请您参考如下方法:
实际上 this回答了我的问题。奇怪的是 bson 包的文档记录如此糟糕。
import json
import bson
to_convert = ["./file1", "./file2"]
for i in to_convert:
INPUTF = i + ".bson"
OUTPUTF = i + ".json"
input_file = open(INPUTF, 'rb', encoding='utf-8')
output_file = open(OUTPUTF, 'w', encoding='utf-8')
raw = (input_file.read())
datas = bson.decode_all(raw)
json.dump(datas, output_file)
