Advertisement
CristianCantoro

Q52672598: Read bson representation into JSON

Mar 25th, 2020
1,470
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.63 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. import re
  4. import json
  5. import tempfile
  6. from bson import json_util
  7. from pprint import pprint
  8.  
  9. example = \
  10. """{
  11.   "_id" : ObjectId("5baca841d25ce14b7d3d017c"),
  12.    "country" : "in",
  13.    "state" : "",
  14.    "date" : ISODate("1902-01-31T00:00:00.000Z")
  15. }"""
  16.  
  17.  
  18. def read_mongoextjson_file(filename):
  19.     with open(filename, "r") as f:
  20.         # read the entire input; in a real application,
  21.         # you would want to read a chunk at a time
  22.         bsondata = f.read()
  23.  
  24.         # convert the TenGen JSON to Strict JSON
  25.         # here, I just convert the ObjectId and Date structures,
  26.         # but it's easy to extend to cover all structures listed at
  27.         # http://www.mongodb.org/display/DOCS/Mongo+Extended+JSON
  28.         jsondata = re.sub(r'ObjectId\s*\(\s*\"(\S+)\"\s*\)',
  29.                           r'{"$oid": "\1"}',
  30.                           bsondata)
  31.         jsondata = re.sub(r'ISODate\s*\(\s*(\S+)\s*\)',
  32.                           r'{"$date": \1}',
  33.                           jsondata)
  34.         jsondata = re.sub(r'NumberInt\s*\(\s*(\S+)\s*\)',
  35.                           r'{"$numberInt": "\1"}',
  36.                           jsondata)
  37.  
  38.         # now we can parse this as JSON, and use MongoDB's object_hook
  39.         # function to get rich Python data structures inside a dictionary
  40.         data = json.loads(jsondata, object_hook=json_util.object_hook)
  41.  
  42.         return data
  43.  
  44.  
  45. if __name__ == '__main__':
  46.  
  47.     with tempfile.NamedTemporaryFile(mode='w+') as temp:
  48.         temp.write(example)
  49.         temp.flush()
  50.  
  51.         data = read_mongoextjson_file(temp.name)
  52.  
  53.     print('data is of type: {}'.format(type(data)))
  54.  
  55.     pprint(data)
  56.  
  57.     exit(0)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement