I’ve found, that the default JSON responses from Phoenix, are not “pretty” (they have no linebreaks across the JSON structure, keys and values are rendered one after another). That might be OK for many use cases, but sometimes your API responses might be better if they can generate “pretty JSON”.
One way to achieve that in Phoenix is by defining following the following function and using it in a controller:
def pretty_json(conn, data) do
conn
|> Plug.Conn.put_resp_header("content-type", "application/json; charset=utf-8")
|> Plug.Conn.send_resp(200, Poison.encode!(data, pretty: true))
end
This can’t be done in a view, though, and leads to lots of repetitions. So if you want to represent a specific view of your data in pretty JSON, you have to do it entirely in the controller, skipping the more usual / recommended render(conn, FooView, "foo.json", data)
pattern.
Maybe there could be an option in the framework to enable pretty JSON by default? Or an additional argument for the render
function that could enable it? Or maybe a plug
that would post-process the result of rendering a view?
Thanks for all your feedback!