用Python读取BSON文件?

Ric*_*ard 7 python mongodb bson

我想在Python中读取BSON格式的Mongo转储并处理数据.我正在使用Python bson包(我更喜欢使用它而不是pymongo依赖),但它没有解释如何从文件中读取.

这就是我正在尝试的:

bson_file = open('statistics.bson', 'rb')
b = bson.loads(bson_file)
print b[0]
Run Code Online (Sandbox Code Playgroud)

但我得到:

Traceback (most recent call last):
  File "test.py", line 11, in <module>
    b = bson.loads(bson_file)
  File "/Library/Python/2.7/site-packages/bson/__init__.py", line 75, in loads
    return decode_document(data, 0)[1]
  File "/Library/Python/2.7/site-packages/bson/codec.py", line 235, in decode_document
    length = struct.unpack("<i", data[base:base + 4])[0]
TypeError: 'file' object has no attribute '__getitem__'
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

njz*_*zk2 7

文件说明:

> help(bson.loads)
Given a BSON string, outputs a dict.
Run Code Online (Sandbox Code Playgroud)

你需要传递一个字符串.例如:

> b = bson.loads(bson_file.read())
Run Code Online (Sandbox Code Playgroud)

  • 这将给出属性错误。bson 不支持加载。我尝试运行它并收到如下错误: AttributeError: module 'bson' has no attribute 'loads' (2认同)

Mar*_*ter 7

我发现这对我有用mongodb 2.4 BSON文件和python的'bson'模块:

import bson
with open('survey.bson','rb') as f:
    data = bson.decode_all(f.read())
Run Code Online (Sandbox Code Playgroud)

这返回了与该mongo集合中存储的JSON文档匹配的字典列表.

f.read()数据在BSON中看起来像这样:

>>> rawdata[:100]
'\x04\x01\x00\x00\x12_id\x00\x01\x00\x00\x00\x00\x00\x00\x00\x02_type\x00\x07\x00\x00\x00simple\x00\tchanged\x00\xd0\xbb\xb2\x9eI\x01\x00\x00\tcreated\x00\xd0L\xdcfI\x01\x00\x00\x02description\x00\x14\x00\x00\x00testing the bu'        
Run Code Online (Sandbox Code Playgroud)

  • 为了使用这个答案的代码,您需要使用 `pip install pymongo` 而不是 `pip install bson` = `pip install pybson`。两者都有“import bson”语句。请参阅 https://github.com/py-bson/bson/issues/70 (4认同)