matiso
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!
Most Liked
michalmuskala
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?
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








