我想从phoenix中的ecto协会生成JSON。从elixir ecto协会创建json
这是我的联想:
defmodule Blog.Post do
use Ecto.Model
schema "posts" do
field :title, :string
field :body, :string
has_many :comments, Blog.Comment
end
end
和:
defmodule Blog.Comment do
use Ecto.Model
schema "comments" do
field :content, :string
belongs_to :post, Blog.Post
end
end
当我产生无关联的JSON的结果是这样的:
[%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看起来像这样
{"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!!!!"
}
]}
,但与联想的结果是这样的
[%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看起来像这样
{"posts": [
{
"title": "the title",
"id": 1,
"body": "the body",
"comments": [{"content": "a comment"}, {"content": "another comment"}]
}
...
]}
任何帮助,将不胜感激。
您使用哪个库来生成JSON?请添加示例代码段。 – 2014-11-07 11:13:54
它是默认的凤凰库,Poison: 'Poison.encode! %{posts:Blog.Repo.all(Blog.Post)}' – idobn 2014-11-07 16:19:53
我假设你得到一个错误,是吗?你可以在这里发布错误吗? – 2014-11-07 18:57:15