如何使用Python将bson文件转换为json文件?

如何使用Python将bson文件转换为json文件?,python,json,bson,Python,Json,Bson,我有一些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', enc

我有一些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.invalidson:bad eoo,这似乎表明文件末尾的NULL字符丢失,但即使我像在注释部分那样手动添加它,错误仍然存在

我如何解决这个问题?

实际上回答了我的问题。奇怪的是,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)
实际上回答了我的问题。奇怪的是,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)

mongodb附带了一个名为的工具,它可以实现以下功能:将BSON文件转换为JSON文件。可能会为您节省一些编码。我没有使用mongodb,我只是有bson转储。mongodb提供了一个名为的工具,它可以实现以下功能:将bson文件转换为JSON文件。可能会为您节省一些编码。我没有使用mongodb,我只是有bson转储。因此我认为此解决方案可行,因为您的文件不是单个bson文档,而是多个未知文档组合在一起。decode_都可以处理这个问题,但是decode是为单个BSON文档设计的。所以我认为这个解决方案是有效的,因为您的文件不是单个BSON文档,而是多个未知文档组合在一起。decode_都可以处理这个问题,但decode是为单个BSON文档设计的。