How to translate a bson file to a json file with Python?
<p>I have some bson files (I don't have the database they came from, just the files, called file1.bson and file2.bson) and I would like to be able to translate them to json. My code is the following:</p>

<pre><code>import json
import bson

to_convert = ["./file1", "./file2"]

for i in to_convert:

    INPUTF = i + ".bson"
    OUTPUTF = i + ".json"

    input_file = open(INPUTF, 'r', encoding='utf-8')
    output_file = open(OUTPUTF, 'w', encoding='utf-8')

    reading = (input_file.read()).encode() #reading = (input_file.read()+'\0').encode()
    datas = bson.BSON.decode(reading)
    json.dump(datas, output_file)
</code></pre>

<p>It raises "bson.errors.InvalidBSON: bad eoo", which seems to indicate the NULL char at the end of a file is missing, but even when I add it manually (as in the commented part) the error persists.</p>

<p>How can I fix this ?</p>

<p>Actually <a href="http://stackoverflow.com/questions/34320177/python-convert-bson-output-of-mongodump-to-array-of-json-objects-dictionaries?rq=1">this</a> answered my question. Weird how poorly documented is the bson package.</p>

<pre><code>import json
import bson

to_convert = ["./file1", "./file2"]

for i in to_convert:

    INPUTF = i + ".bson"
    OUTPUTF = i + ".json"

    input_file = open(INPUTF, 'rb', encoding='utf-8')
    output_file = open(OUTPUTF, 'w', encoding='utf-8')

    raw = (input_file.read())
    datas = bson.decode_all(raw)
    json.dump(datas, output_file)
</code></pre>

python json bson