从elixir ecto协会创建json

前端之家收集整理的这篇文章主要介绍了从elixir ecto协会创建json前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想从凤凰城的ecto协会生成 JSON.

这是我的协会:

  1. defmodule Blog.Post do
  2. use Ecto.Model
  3.  
  4. schema "posts" do
  5. field :title,:string
  6. field :body,:string
  7. has_many :comments,Blog.Comment
  8. end
  9. end

和:

  1. defmodule Blog.Comment do
  2. use Ecto.Model
  3.  
  4. schema "comments" do
  5. field :content,:string
  6. belongs_to :post,Blog.Post
  7. end
  8. end

当我生成没有关联的json时,结果如下:

  1. [%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看起来像这样

  1. {"posts": [
  2. {
  3. "title": "first post","id": 1,"body": "this is the very first post ever!"
  4. },{
  5. "title": "hi Nimrod","id": 12,"body": "Hello nimrod!!!!"
  6. },{
  7. "title": "hello(edit)","id": 6,"body": "editing the body!!!!"
  8. }
  9. ]}

但结果就是结果

  1. [%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]>},title: "hello(edit)"}]

使用上面的输出我无法创建适当的json输出.我想让json看起来像这样

  1. {"posts": [
  2. {
  3. "title": "the title","body": "the body","comments": [{"content": "a comment"},{"content": "another comment"}]
  4. }
  5. ...
  6. ]}

任何帮助,将不胜感激.

解决方法

哎呀,目前还没有简单的解决方案.我会尝试类似的东西:
  1. defimpl Poison.Encoder,for: Tuple do
  2. def encode(proxy,options) do
  3. Poison.Encoder.List.to_json(proxy.all,options)
  4. end
  5. end

我们基本上为元组实现编码器,接收上面的代理并编码所有项目.我们需要为此讨论更好的解决方案.

猜你在找的JavaScript相关文章