我试图简单地在模板中显示一些数据。但显然我错过了一步。
使用 HTTPoison 请求
use HTTPoison.Base
@expected_fields ~w(result)
def process_url(url) do
"url.json"
end
def process_response_body(body) do
body
|> Poison.decode!
|> Map.take(@expected_fields)
|> Enum.map(fn({k ,v}) -> {String.to_atom(k), v} end)
end
Controller
def index(conn, _params) do
response = ApiTest.get!("").body[:result]
render conn, "index.html", response: response
end
模板
<%= @response %>
错误是: Phoenix.HTML 和模板中的列表只能包含表示字节、二进制或其他列表的整数,获得无效条目
那么在哪里将数据转换为可以在模板中显示的格式呢?
最佳答案
从错误消息来看,它看起来像 result
响应 JSON 中的键是列表或包含列表。如果您想要输出用于调试,两种常见的方法是使用 Kernel.inspect
得到类似于 iex
中的表示形式或Poison.encode!
获取 JSON 表示:
<%= inspect(@response) %>
或
<%= Poison.encode!(@response) %>
您可能想将整个内容包装在 <pre>
中标签以获得 inspect
中精美包装的输出:
<pre><%= inspect(@response) %></pre>
或者这样做+添加pretty: true
对于 Poison.encode!
:
<pre><%= Poison.encode!(@response, pretty: true) %></pre>
关于elixir - 在 Phoenix 模板中显示 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38544069/