Tsonnet #5 - Pretty-printing JSON
Replacing manual string formatting with a robust JSON pretty-printing solution
Welcome to the Tsonnet series!
In the previous post, we refactored numerical types:
Today, I'd like to tackle the presentation layer: pretty-printing the JSON output.
The print function is not actually printing "JSON", just raw value representations.
Yojson is a pretty common choice for parsing JSON in OCaml.
Let's install it with opam:
And add it to our dependencies in dune-project:
The opam file is automatically updated by dune.
Before using the library, we need to specify that the lib config will depend on yojson:
To get rid of the printfs, we need a way of converting a expr to JSON.
Let's encapsulate the expression conversion in a new module, dedicated to transforming expressions into JSON representation:
The new `Json` module will implement two functions. The function expr_to_yojson basically maps our expr types to Yojson.t. The function expr_to_string will use the previous function to convert from Yojson.t to string.
If eventually we decide to change the way we want to render JSON, like using a more performant library, for example, we refactor this module and there's no need to update anywhere else -- maybe the tests.
With that, we can remove our messy hand-written print function:
The Tsonnet library module looks much cleaner!
As we are making the run function return a string, we must update main.ml
accordingly:
And the cram tests need to reflect the output as well:
One trick that makes our lives super easy is the fact that dune has a feature called promote.
What does it do? If the tests run and the output is correct, but the diff is conflicting, you have the option to promote it, which means that it will apply the diff for you with a single command:
The command above will re-run the tests and apply the diff of the output to the respective files.
This is super handy! I won't go into details here, but I really recommend reading the Diffing and Promotion documentation.
Beware, this can make you grumpy against your current building tool -- approach with caution. It feels like magic, really! ๐
It feels much better having a pretty printed output, isn't it?!