Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A tool for pretty printing bson string (e.g., output of mongoexport)
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from bson import json_util, ObjectId
from bson.py3compat import string_types
from bson.dbref import DBRef
def format(bson, indent=DEFAULT_INDENT):
d = _dbref_fix(json_util.loads(l))
return json_util.dumps(d, indent=indent)
def parse(infile, outfile, indent=DEFAULT_INDENT):
for l in infile:
print(format(l, indent=indent), file=outfile)
def _dbref_fix(obj):
Recursive helper method that converts BSON ObjectId types so they can be
converted by bson.json_util.dumps into json.
Created to deal with a situation like this:
"collection" : { "$ref" : "collection", "$id" : { "$oid" : "505cdd127e89297d6f000421" } }
if hasattr(obj, 'iteritems') or hasattr(obj, 'items'): # PY3 support
return {k: _dbref_fix(v) for k, v in obj.iteritems()}
elif hasattr(obj, '__iter__') and not isinstance(obj, string_types):
return [_dbref_fix(v) for v in obj]
elif isinstance(obj, DBRef):
id =
coll = obj.collection
db = obj.database
d = {}
if id: d['$id'] = {'$oid': str(id)}
if coll: d['$ref'] = coll
if db: d['$db'] = db
return d
return obj
if __name__ == '__main__':
import sys
import argparse
parser = argparse.ArgumentParser(description='Pretty print bson dumps.')
parser.add_argument('-i', '--indent', type=int, default=DEFAULT_INDENT, help='Number of spaces to indent')
parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
args = parser.parse_args()
parse(args.infile, args.outfile, args.indent)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment