14

Is there a shell one-liner to convert JSON to BSON?

Something suitable for one-off execution, or a shell script?

bsondump from MongoDB goes the inverse way, but I'm clueless as to what I can use to go from JSON to BSON. There's no bsonundump, e.g.

nmr
  • 262
  • This is definitely not a programming question, I view it as a tools question, but I admit that the distinction is subjective. I am open to other suggestions. – nmr May 14 '14 at 20:23

4 Answers4

18

Converting JSON to BSON

There's this C implementation that includes a Makefile called json2bson.c.

Converting BSON to JSON

The MongoDB project provides a tool called bsondump.

The bsondump converts BSON files into human-readable formats, including JSON. For example, bsondump is useful for reading the output files generated by mongodump.

Usage

$ bsondump collection.bson > collection.json

There's also this Ruby script I found called bson2json.rb to convert BSON to JSON as well.

slm
  • 369,824
  • @nmr - I did find a method using a C app to do JSON to BSON. – slm May 14 '14 at 21:08
  • Where does bson.h come from? – Jonathan Hartley Jul 09 '20 at 21:09
  • Believe it's part of a mongo library, look at the Makefile. – slm Jul 10 '20 at 03:23
  • Difference between JSON and BSON is that BSON is more rich on data types + is binary. If there are some tools for this, you cannot be 100% sure about the result. Having following json { "number": 123 } You can't be sure whether number 123 is int or long without proper knowledge of schema. MongoDB know what the number is because you specify NumberLong() or NumberInt() when You're working with the document. – Jakub Jindra Aug 25 '20 at 13:07
2

You can try beesn, it converts data both ways. For JSON -> BSON use the -x switch.

Example:

$ beesn -x -i test-data/01.json -o my.bson

Disclaimer: I am an author of this tool.

menfon
  • 232
  • Is beesn dead or just mature? There has been no activity in the repository for over two years, but there are also no open issues or merge requests, so maybe it is just working, and there is nothing to improve / change? – Jörg W Mittag Nov 26 '20 at 19:35
  • 1
    @JörgWMittag I think mature. I haven't received any bug reports, tests are passing. The tool itself is very small, just 150 LoC, because it relies heavily on other libraries. – menfon Nov 27 '20 at 08:02
2

Yes, I've made tool for this :) https://mmalcek.github.io/bafi/

The simplest oneline is ./bafi -i inFile.json -f json -t '?{{ toBSON . }}' -o outFile.bson but there are a lot of other options including stdin/stdout

Mario
  • 21
-2

This shell script converts all the bson files in the dump directory to json files

mongodump
for j in ./dump/*
do
 echo Working on directory "$j"
 for i in "$j"/*.bson
 do
  echo Working on file "$i"
  bsondump "$i" >> "$(echo "$i" | sed -e 's/\.bson.*$//')".json
  done
done