Json/2 vs render/3

Hello.

I’m confused with which to use json/2 or render/3. I think json/2 is easy to use, and render/3 is easy to read. But I often see developers use render/3 more than json/2.

I use render/3 basically. I use json/2 when the data whose key is not atom but string.

What do you think of that?

I recently started working with elixir/phoenix so take my opinion with a pinch of salt.

I think it’s ok to use json/2 if you are returning simple json structure like {"message": "Error"} and use render/3 when you have to return complex json structure like { "data": { "name": "demo_user_1"}}

1 Like

render does a lot of things - content-type negotiation (if you pass an atom for the template name), layouts (for text/html responses), and expects a corresponding render head in the view module.

json doesn’t do any of that, so it’s useful for cases where the data’s already in the right shape to be converted to JSON (or short enough, like in @sushant12’s example).

3 Likes
  • Does it need to handle different content type (e.g. by accept request header)? => use render/3
  • Does it need to have template to handle complicated rendering? => use render/3

If not - it’s okay to use json/2. Actually I haven’t used render/3 in API services :wink:

1 Like