Considerations when Storing C# code in JSON
iKnode‘s main database has always been Postgresql, but recently we have been using MongoDB more and more. Currently we store C# code in Postgresql, which is painless, since we can just grab the input directly from the Web editor and into the the database unmodified. With MongoDb, this process is not as easy because MongoDB depends on a JSON-like format.
MongoDB stores data using BSON, which is a superset of JSON. While testing, we needed to set the default Database state to run our tests, we encountered a couple of problems while serializing C# code into JSON.
We followed these considerations to transform C# code so that it could be embedded in a JSON string:
- Convert Tabs to Spaces. (In Emacs you can do this with the M-x untabify command)
- Escape carrier returns (\n -> \\n) (In emacs yo ucan do this by replacing C-qj with \\n)
- Escape double qoutes (” -> \”).
The next things we did was validate the resulting JSON. You can do this with a web JSON Formatter like CuriousConcept’s JSON Formatter. We tried others like JSONLint, but the only one that gave us a detailed error description was CuriousConcept’s JSON Formatter.
In the end we now have C# code in a JSON store. Hope this helps anyone trying to do store c-like type code.