How to ignore nil values in response in Phoenix

Hey folks! I have a web service in Phoenix that returns responses in JSON format. I want Phoenix to ignore nil values in the JSON response and return only fields populated with data. This problem looks so common. Is there a Phoenix setting to ignore nil values in the response? If not can anyone recommend a plug?

Example. I have an endpoint GET /foo/ that returns {“foo”: “something”, “bar”: nil }. I want Phoenix to return {“foo”: “something”} and ignore the “bar” field.

PS I’m new in Elixir and Phoenix.

1 Like

Usually you’d use views to convert data fetched in the controller to something returned as a response. For json those view functions return maps of the data you want in your response. You can manipulate that map however you need.

For some more context see this: Phoenix Views for JSON APIs | Benjamin Milde

2 Likes