无法使用 bson 模块将 python 2.7 中的 bson 转换为 json

Cant convert bson to json in python 2.7 using bson module

无法从 bson 文件转换为 json 对象。 bson 文件:https://s3.amazonaws.com/orim-misc-data/assessment/books.bson

我想将 Bson 文件转换为 Json 对象。但是当我使用 bson 模块和附加文件时出现异常,

INPUTF = "books.bson"
input_file = io.open(INPUTF, 'r', encoding='utf-8',errors='ignore')
datas = bson.loads(input_file.read())

BSON 不能完全替代 JSON。

BSON 是二进制对象格式,而不是文本格式(即使它确实存储 UTF-8 编码的字符串)

你的开启器应该反映二进制模式

# input_file = io.open(INPUTF, 'r', encoding='utf-8',errors='ignore')  # old
input_file = io.open(INPUTF, 'rb')
                               ^
                               | (b opens the file in binary mode
--------------------------------   does not need the rest of the encoding/error params)

您需要调用 bson.decode_all(data) 函数而不是加载 s

# datas = bson.loads(input_file.read()) # old
datas = bson.decode_all(input_file.read()) # python list object

如果您的管道支持,强烈建议您考虑 bson.decode_iter

#datas = bson.loads(input_file.read()) # old
datas = bson.decode_file_iter(input_file) # python generator object
for document in datas:
    # do something with each document
    # very easy on system io and memory