首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从elixir ecto关联创建json

从elixir ecto关联创建json
EN

Stack Overflow用户
提问于 2014-11-07 00:07:36
回答 1查看 2.2K关注 0票数 7

我想从凤凰城的一个ecto协会生成JSON。

这是我的联想:

代码语言:javascript
复制
defmodule Blog.Post do
  use Ecto.Model

  schema "posts" do
    field :title, :string
    field :body, :string
    has_many :comments, Blog.Comment
  end
end

和:

代码语言:javascript
复制
defmodule Blog.Comment do
  use Ecto.Model

  schema "comments" do
    field :content, :string
    belongs_to :post, Blog.Post
  end
end

当我在没有关联的情况下生成json时,结果是:

代码语言:javascript
复制
[%Blog.Post{body: "this is the very first post ever!", id: 1,title: "first post"},
 %Blog.Post{body: "Hello nimrod!!!!", id: 12, title: "hi Nimrod"},
 %Blog.Post{body: "editing the body!!!!", id: 6, title: "hello(edit)"}]

json看起来像这样

代码语言:javascript
复制
{"posts": [
    {
        "title": "first post",
        "id": 1,
        "body": "this is the very first post ever!"
    },
    {
        "title": "hi Nimrod",
        "id": 12,
        "body": "Hello nimrod!!!!"
    },
    {
        "title": "hello(edit)",
        "id": 6,
        "body": "editing the body!!!!"
    }
]}

但是这种关联的结果是这样的

代码语言:javascript
复制
[%Blog.Post{body: "this is the very first post ever!",
 comments: {Ecto.Associations.HasMany.Proxy,
 #Ecto.Associations.HasMany<[name: :comments, target: Blog.Post,
 associated: Blog.Comment, references: :id, foreign_key: :post_id]>}, id: 1,
 title: "first post"},
 %Blog.Post{body: "Hello nimrod!!!!",
 comments: {Ecto.Associations.HasMany.Proxy,
 #Ecto.Associations.HasMany<[name: :comments, target: Blog.Post,
 associated: Blog.Comment, references: :id, foreign_key: :post_id]>}, id: 12,
 title: "hi Nimrod"},
 %Blog.Post{body: "editing the body!!!!",
 comments: {Ecto.Associations.HasMany.Proxy,
 #Ecto.Associations.HasMany<[name: :comments, target: Blog.Post,
 associated: Blog.Comment, references: :id, foreign_key: :post_id]>}, id: 6,
 title: "hello(edit)"}]

使用上面的输出,我不能创建正确的json输出。我希望json看起来像这样。

代码语言:javascript
复制
{"posts": [
     {
        "title": "the title",
        "id": 1,
        "body": "the body",
        "comments": [{"content": "a comment"}, {"content": "another comment"}]
     }
     ...
]}

任何帮助都将不胜感激。

EN

回答 1

Stack Overflow用户

发布于 2014-11-08 21:07:03

哎呀,目前还没有简单的解决方案。我会尝试这样的方法:

代码语言:javascript
复制
defimpl Poison.Encoder, for: Tuple do
  def encode(proxy, options) do
    Poison.Encoder.List.to_json(proxy.all, options)
  end
end

我们基本上是为接收上述代理的元组实现编码器,并对所有项进行编码。我们需要讨论更好的解决方案。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26784000

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档