Search code examples
jsonmongodbgsonmongoexport

BSON produced by mongoexport from Mongodb is not a valid JSON


I am new to Mongo and trying to export a JSON file from a collection. The > MONGOEXPORT worked well and created a JSON file.

{ "_id" : { "$oid" : "54c8f3fb5e24e03c473243c4" }, "username" : "Aman", "password" : "yesboss" }
{ "_id" : { "$oid" : "54c901c1953b434dabadbabf" }, "username" : "AMAN2" }

Now, JSONLint shows me the error that it is not a valid JSON.

I need this to import in my Java Project to extract values from it.


Solution

  • MongoExport exports valid JSON. Your Java should parse each line, instead of the whole file, as a JSON object.

    If you want to treat the entire export file as a JSON object, then use the option --jsonArray

    --jsonArray
    output to a json array rather than one 
    object per line
    

    Example:

    mongoexport --db test -c x
    connected to: 127.0.0.1
    { "_id" : "54c8f3fb5e24e03c473243c4", "username" : "Aman", "password" : "yesboss" }
    { "_id" : "54c901c1953b434dabadbabf", "username" : "AMAN2" }
    exported 2 records
    
    mongoexport --db test -c x --jsonArray
    connected to: 127.0.0.1
    [{ "_id" : "54c8f3fb5e24e03c473243c4", "username" : "Aman", "password" : "yesboss" },{ "_id" : "54c901c1953b434dabadbabf", "username" : "AMAN2" }]
    exported 2 records