Pretty printing JSON as an option for Phoenix

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!

You can set a custom format encoder to a module, where you’d call Poison.encode(data, pretty: true).

config :phoenix, :format_encoders,
  html: Phoenix.HTML.Engine,
  json: PrettyJson

The documentation is here in the “Format encoders” section.

I wonder what’s the use case of emitting a prettified JSON. Is it to make it human readable?

2 Likes

This is great, thank you!

Yes, that’s pretty much it. Of course it’s not strictly necessary, but it makes it easier for copying & sending data to people when you don’t have a proper UI for it.

I use a plugin in chrome to view JSON well (with lots of cool options) and a pretty prettier that I can pipe curl into for the command prompt, why would you want to inflate the network usage?

I’m using ProperCase dependency. It’s lightweight and easy to config.