Search code examples
pythonbson

Check if a string is valid BSON in python


The way I used to do this was to run this function

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               

This no longer works, because the bson library has no attribute 'binary'


Solution

  • you appear to be using a 3rd party py-bson, perhaps due to pip install bson.

    https://github.com/py-bson

    rather than mongodb supported python-bson pip install pymongo.

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

    Note install:

    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.

    You can either switch to the mongodb version of bson and your function will simply work, or change your is_binary function to accommodate the fact that pybson decodes everything to strings in python2 and bytes in python3.

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