在 python 中检查字符串是否为有效的 BSON

Check if a string is valid BSON in python

我以前这样做的方法是运行这个函数

import bson 

def has_binary(d):
if type(d)==bson.Binary:
    return True
if type(d)==dict:
    for k,v in d.iteritems():
        if has_binary(v):
            return True
return False               

这不再有效,因为 bson 库没有属性 'binary'

您似乎在使用第 3 方 py-bson,可能是由于 pip install bson

https://github.com/py-bson

而不是 mongodb 支持 python-bson pip install pymongo.

https://github.com/mongodb/mongo-python-driver/tree/master/bson

注意安装:

PyMongo can be installed with pip:

$ python -m pip install pymongo

Do not install the “bson” package. PyMongo comes with its own bson package; doing “easy_install bson” installs a third-party package that is incompatible with PyMongo.

您可以切换到 bson 的 mongodb 版本并且您的函数将简单地工作,或者更改您的 is_binary 函数以适应 pybson 将所有内容解码为 [=31= 中的字符串这一事实]2 和 python3.

中的字节

https://github.com/py-bson/bson/blob/master/bson/codec.py#L303-L307