So we’re building this JSON API at autobutler.dk, in which we want the JSON outputted to be human readable (pretty).
Nothing is worse than trying to debug a JSON service, and always having to parse it through e.g.
Instead we just want the service to output the pretty JSON. It doesn’t consume a lot of resources to do so, and the pretty JSON is equivalent to the non-pretty one, that is the following are the same:
In this simple example it doesn’t really matter, but this JSON is entirely unreadable:
while this is not
To create this JSON API we’re using Grape.
When defining the response format in Grape as
:json, it automatically calls
to_json on the objects returned by the controller.
So in our
app.rb we just do
Now everything is “ugly” JSON.
To get pretty JSON, we have to create our own formatter, overriding Grape’s default.
PrettyJSON formatter could look like:
and then to use it, all we have to do is tell Grape:
The trained programmer will notice something weird about the
Why are we calling
object.to_json and then parsing this as JSON, resulting in an hash again?
This is because we can have nested objects, which
JSON.pretty_generate cannot seem to handle, however
JSON.parse(object.to_json) will not give us nested objects, but rather nested hashes (yeah, hashes are objects too) which can be prettified by JSON.
Thus, with just 6 lines of extra code, we can have pretty JSON in our Grape API app.