Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash - Convert MONGODB BSON to JSON

Tags:

json

mongodb

bson

I have a shell command that calls a MongoDB command and produces a BSON output. I then want to parse that output with jq so I need to convert the BSON to JSON using jq's tojson.

echo "db._adminCommand({replSetGetStatus : 1})" | /path/to/mongo

How do I implement tojson is it as simple as doing this say:

echo "db._adminCommand({replSetGetStatus : 1})" | /path/to/mongo | jq '[.[]|tojson]'

I haven't put jq on my server yet as I have to prove it works before I can get it released.

When I try .[]|tojson in the online demo it doesn't work but I wasn't sure if this was a demo limitation?

EDIT

So I managed to get "jq" on a test server running mongodb and tried this:

echo "db._adminCommand({replSetGetStatus : 1})" | /path/to/mongo | ./jq '.members[] | {Server: .name, State: .stateStr}'

The error I received was this:

parse error: Invalid numeric literal at line 1, column 8

So it would appear that "jq" can not parse the data from replSetGetStatus.

In the mean time as I sit back scratching my head, waiting for the Change Management Death Squads to turn up, if anyone has some ideas they would be greatly appreciated.

like image 309
SnazzyBootMan Avatar asked Oct 16 '14 12:10

SnazzyBootMan


People also ask

Can you convert BSON to JSON?

Converting a BSON Object to a JSON StringUse the asString method to convert the BSON document to an extended JSON string. See http://docs.mongodb.org/manual/reference/mongodb-extended-json/ for more information on extended JSON.

Why does MongoDB use BSON rather than JSON?

BSON's binary structure encodes type and length information, which allows it to be traversed much more quickly compared to JSON. BSON adds some non-JSON-native data types, like dates and binary data, without which MongoDB would have been missing some valuable support.

How do I read a BSON file?

If you cannot open your BSON file correctly, try to right-click or long-press the file. Then click "Open with" and choose an application. You can also display a BSON file directly in the browser: Just drag the file onto this browser window and drop it.


1 Answers

You can use bsondump utility coming with mongodb:

bsondump yourfile.bson | head
like image 144
Alexander Sirenko Avatar answered Sep 19 '22 17:09

Alexander Sirenko