MongoDB.live, free & fully virtual. June 9th - 10th. Register Now MongoDB.live, free & fully virtual. June 9th - 10th. Register Now

Format and colorize JSON

We post a lot of JSON on this forum. It would be nice to have that JSON formatted better with pretty colors. It would also be nice to have shell commands (e.g. db.col.find({ a: 1 })) highlighted and colored in a user friendly way.

1 Like

Hi Justin,

You can use fenced code blocks similar to Github markdown for improved formatting including syntax highlighting.

Place triple backticks (```) before and after a block of text to style it using automatic language detection.

Borrowing a code sample from the MongoDB manual:

db.inventory.insertMany([
   { item: "journal", qty: 25, status: "A", size: { h: 14, w: 21, uom: "cm" }, tags: [ "blank", "red" ] },
   { item: "notebook", qty: 50, status: "A", size: { h: 8.5, w: 11, uom: "in" }, tags: [ "red", "blank" ] },
   { item: "paper", qty: 10, status: "D", size: { h: 8.5, w: 11, uom: "in" }, tags: [ "red", "blank", "plain" ] },
   { item: "planner", qty: 0, status: "D", size: { h: 22.85, w: 30, uom: "cm" }, tags: [ "blank", "red" ] },
   { item: "postcard", qty: 45, status: "A", size: { h: 10, w: 15.25, uom: "cm" }, tags: [ "blue" ] }
]);

If auto-detection doesn’t work well for a code snippet (or you want to be more declarative), you can provide a hint on a language formatting to use by adding the formatter (json, javascript, yaml, … ) after the opening backticks.

For example, javascript formatting adds highlighting for numeric values to this code sample:

db.inventory.insertMany([
   { item: "journal", qty: 25, status: "A", size: { h: 14, w: 21, uom: "cm" }, tags: [ "blank", "red" ] },
   { item: "notebook", qty: 50, status: "A", size: { h: 8.5, w: 11, uom: "in" }, tags: [ "red", "blank" ] },
   { item: "paper", qty: 10, status: "D", size: { h: 8.5, w: 11, uom: "in" }, tags: [ "red", "blank", "plain" ] },
   { item: "planner", qty: 0, status: "D", size: { h: 22.85, w: 30, uom: "cm" }, tags: [ "blank", "red" ] },
   { item: "postcard", qty: 45, status: "A", size: { h: 10, w: 15.25, uom: "cm" }, tags: [ "blue" ] }
]);

There currently isn’t a specific formatter for mongo shell code (which isn’t strictly JavaScript in interpretive mode), but the javascript formatter should handle this OK.

Most of the formatters listed for Highlight.js should be supported.

Since our forum discussion involves many different programming languages and formats, the default is auto-detection rather than JavaScript.

Regards,
Stennie

3 Likes

Aha! That makes sense.

Thanks for the detailed reply!

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.