Danny Ocean
Danny Ocean

Reputation: 1121

How to avoid json decoding in phoenix while sending json response?

For example, I have an API client that returns json (as a string, not decoded). Currently, I have to do something like this

def show(conn, params) do
  {:ok, json} = ApiClient.fetch(params["options"])

  json conn, Poison.decode!(json)
end

If I avoid Poison.decode then the response will be a huge string instead of json. Can I omit Poison.decode somehow? It looks as an excessive action for me.

Note: I'm on phoenix 1.3.0

Upvotes: 2

Views: 1912

Answers (1)

Gazler
Gazler

Reputation: 84150

The json/2 function can send any serializable data structure as JSON (including a string).

Your APIClient.fetch function is not JSON decoding the response, however if the string is already JSON, there is no need to decode it. You can send it directly using send_resp/3:

send_resp(conn, 200, json)

You may also need to set the content type using put_resp_content_type/3:

conn
|> put_resp_content_type("application/json")
|> send_resp(200, json)

Since the json/2 function encodes the data as JSON, assuming the JSON string:

"{\"hello\":\"world\"}"

You would be encoding it twice, resulting in:

"\"{\\\"hello\\\":\\\"world\\\"}\""

Upvotes: 4

Related Questions