0

我无法对从 Ecto 查询结果毒药编码方法获得的值进行编码

控制器代码:

def companies(conn, params) do
    companies = Repo.all(
      from(
        c in Company,
        select: {c.name, c.uid},
        limit: 20
      )
    ) 

    conn
    |> put_resp_header("content-type", "application/json; charset=utf-8")
    |> send_resp(200, Poison.encode!(companies, pretty: true))
end

模板代码:

<div class="form-group row">
  <%= label f, :company_id, class: "control-label" %>
  <%= select f, :company_id, @companies, class: "form-control"%>
<%= error_tag f, :company_id %>

错误信息:

Request: GET /companies
** (exit) an exception was raised:
    ** (Poison.EncodeError) unable to encode value: {"Loews Corporation", 1000285930}
        (poison) lib/poison/encoder.ex:383: Poison.Encoder.Any.encode/2
        (poison) lib/poison/encoder.ex:268: anonymous fn/4 in Poison.Encoder.List.encode/3
        (poison) lib/poison/encoder.ex:269: Poison.Encoder.List."-encode/3-lists^foldr/2-0-"/3
        (poison) lib/poison/encoder.ex:269: Poison.Encoder.List.encode/3
        (poison) lib/poison.ex:41: Poison.encode!/2
4

2 回答 2

2

添加到@Dogbert 的答案:您还可以通过生成手动返回map的内容来生成 JSON 对象:Ecto

companies =
  from(c in Company, select: {c.name, c.uid}, limit: 20)
  |> Repo.all()     # returning list of tuples
  |> Enum.into(%{}) # this

#⇒ %{"Loews Corporation" => 1000285930, "Foo" => 1, "Bar" => 2}

地图可以用 编码为 JSON Poison,生成 JS 对象。

于 2018-04-13T16:56:16.367 回答
2

Poison 无法将元组编码为 JSON 值。如果您想要[{name: ..., uid: ...}, {name: ..., uid: ...}]生成的 JSON,您可以在查询中使用map()或映射文字select

select: map(c, [:name, :uid])

或者

select: %{name: c.name, uid: c.uid}
于 2018-04-13T16:44:44.510 回答