h8rt3rmin8r

bson2json.rb

Aug 5th, 2018
171
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/ruby
  2.  
  3. # This script acts as a command-line filter to convert a BSON file (such as from mongodump) to an equivalent JSON file
  4. # The resulting JSON file will be an array of hashes
  5. # Any binary values from the BSON file are converted to base64 (such as Mongo's _id fields)
  6. # I originally wrote this script so that Mongo files can be easily used with jsawk for
  7. # offline data processing -- https://github.com/micha/jsawk
  8. #
  9. # To invoke, assuming mycollection.bson is a file from mongodump:
  10. #   ruby bson2json.rb  < mycollection.bson > mycollection.json
  11.  
  12. require 'rubygems'
  13. require 'bson'
  14. require 'json'
  15. require 'base64'
  16.  
  17. def process(file)
  18.   puts '['
  19.  
  20.   while not file.eof? do
  21.     bson = BSON.read_bson_document(file)
  22.     bson = bson_debinarize(bson)
  23.     puts bson.to_json + (file.eof? ? '' : ',')
  24.   end
  25.  
  26.   puts ']'
  27. end
  28.  
  29. # Accept BSON document object; return equivalent, but with any BSON::Binary values converted with Base64
  30. def bson_debinarize(bson_doc)
  31.   raise ArgumentError, "bson_doc must be a BSON::OrderedHash" unless bson_doc.is_a?(BSON::OrderedHash)
  32.  
  33.   # each key and value is passed by reference and is modified in-place
  34.   bson_doc.each do |k,v|
  35.     if v.is_a?(BSON::Binary)
  36.       bson_doc[k] = Base64.encode64(v.to_s)
  37.     elsif v.is_a?(BSON::OrderedHash)
  38.       bson_doc[k] = bson_debinarize(v)
  39.     end
  40.   end
  41.  
  42.   bson_doc
  43. end
  44.  
  45. process(STDIN)
  46.  
  47. __END__
  48.  
  49. Copyright (c) 2012 SPARC, LLC
  50.  
  51. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  52.  
  53. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  54.  
  55. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
RAW Paste Data