Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert BSON to valid JSON [duplicate]

The BsonDocument.ToJson() method returns invalid JSON, as ObjectID() and ISODate are not valid JSON.

What's the best way to get valid JSON from an arbitary BSON document?

like image 779
BanksySan Avatar asked Feb 11 '16 22:02

BanksySan


People also ask

Can you convert BSON to JSON?

Can I convert BSON to JSON? Converting a BSON Object to a JSON String Use 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.

Can JSON have duplicate values?

We can have duplicate keys in a JSON object, and it would still be valid. The validity of duplicate keys in JSON is an exception and not a rule, so this becomes a problem when it comes to actual implementations.

How does JSON handle duplicate keys?

In the case where there are duplicate name Strings within an object, lexically preceding values for the same key shall be overwritten. In other words, last-value-wins. Save this answer.

Is BSON better than JSON?

BSON is also designed to be fast to encode and decode. For example, integers are stored as 32 (or 64) bit integers, so they don't need to be parsed to and from text. This uses more space than JSON for small integers, but is much faster to parse.


1 Answers

You can try something like this

var document = new BsonDocument("_id", ObjectId.GenerateNewId());
    var jsonWriterSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict }; // key part
    Console.WriteLine(document.ToJson(jsonWriterSettings));

For More info https://groups.google.com/forum/#!topic/mongodb-user/fQc9EvsPc4k

like image 194
Mainul Avatar answered Oct 10 '22 01:10

Mainul