A simple BSON indenter / compacter
the goal of this code is not to check if a document has a valid BSON syntax


But that's the first requirement of a formatter, understanding the syntax. For any formatter to work, it must understand the structure of the input. For instance, if I stick a { inside some random string, how would case "{": tell it apart from a structural {?

So in some form, your parser, no matter how simple, would need to know about some of these rules. You don't need to build a robust parser, you just need to know where the current character is based characters already encountered.

You can use JSON's flow diagrams as a guide to know when it's possible to encounter such characters. You just need to extend it for BSON. Also, here's a simple JS comment remover which removes comments from JS without having to understand the entire JS syntax. In a gist, it went through the string, checking the current character against the current state (i.e. am I in a string, a regexp, comment, etc.) then modifying the code accordingly as it went through.