我有一个语言模型,我希望将所有语言作为json,但json输出如下所示
[{ “语言”:{ “created_at”:空, “ID”:1, “语言”: “英语”, “的updated_at”:空}},{ “语言”:{ “created_at”:空, “ID”:2, “语言”: “瑞典”, “的updated_at”:空}},{ “语言”:{ “created_at”:空, “ID”:3, “语言”: “德国”,“的updated_at “:空}},{” 语言 “:{” created_at “:空,” ID “:4,” 语言 “:” 法国”, “的updated_at”:空}},{ “语言”:{ “created_at”:空, “ID”:5, “语言”: “西班牙语”, “的updated_at”:空}},{ “语言”:{ “created_at”:空, “ID”:6, “语言”: “荷兰”, “的updated_at”:空}},{ “语言”:{ “created_at”: “2012-12-03T05:01:18Z”, “ID”:7, “语言”: “泰米尔语”, “的updated_at”:“2012 -12-03T05:01:18Z“}}]
但我希望将其作为
{ “语言”:[{ “created_at”:空, “ID”:1, “语言”: “英语”, “的updated_at”:空},{ “created_at”:空, “ID”:2, “语言”: “瑞典”, “的updated_at”:空},{ “created_at”:空, “ID”:3, “语言”: “德国”, “的updated_at”:空},{ “created_at”:空, “ID”:4, “语言”: “法国”, “的updated_at”:空},{ “created_at”:空, “ID”:5, “语言”: “西班牙”, “的updated_at”:空},{ “created_at”:空, “ID”:6, “语言”: “荷兰人”, “的updated_at”:空},{ “created_at”:空, “ID”:7, “语言”: “泰米尔语”,“的updated_at “:null}]}
更新
def index
@languages = Language.all
respond_to do |format|
format.json { render json: @languages}
end
end
更新2
class Language < ActiveRecord::Base
ActiveRecord::Base.include_root_in_json = false
has_and_belongs_to_many :users
end
答案 0 :(得分:14)
我相信这应该有效:
format.json { render json: { "language" => @languages.as_json(:root => false) }.to_json }
将@languages
数组转换为没有根密钥的JSON格式散列模型数组(使用as_json
),然后将结果包装为带有根密钥的散列“语言“,并将该哈希值转换为to_json
的JSON格式字符串。 (有关使用as_json
包含或不包含根节点的详细信息,请参阅the docs。)
例如,使用模型Post
:
posts = Post.all
#=> [#<Post id: 1, name: "foo", title: "jkl", content: "some content", created_at: "2012-11-22 01:05:46", updated_at: "2012-11-22 01:05:46">]
# convert to array of hashes with no root keys
posts.as_json(root: false)
#=> [{"content"=>"some content", "created_at"=>Thu, 22 Nov 2012 01:05:46 UTC +00:00, "id"=>1, "name"=>"foo", "title"=>"jkl", "updated_at"=>Thu, 22 Nov 2012 01:05:46 UTC +00:00}]
# add root back to collection:
{ "post" => posts.as_json(root: false) }
#=> {"post"=>[{"content"=>"some content", "created_at"=>Thu, 22 Nov 2012 01:05:46 UTC +00:00, "id"=>1, "name"=>"foo", "title"=>"jkl", "updated_at"=>Mon, 03 Dec 2012 09:41:42 UTC +00:00}]}
# convert to JSON-formatted string
{ "post" => posts.as_json(root: false) }.to_json
#=> "{\"post\":[{\"content\":\"some content\",\"created_at\":\"2012-11-22T01:05:46Z\",\"id\":1,\"name\":\"foo\",\"title\":\"jkl\",\"updated_at\":\"2012-12-03T09:43:37Z\"}]}"
答案 1 :(得分:2)
我建议您使用rabl gem(https://github.com/nesquena/rabl)来格式化数据。
答案 2 :(得分:2)
覆盖您要自定义的模型上的as_json
def as_json options={}
{
id: id,
login: login,
name: custom.value, #for custom name
...
}
end
==> or
def as_json(options={})
super(:only => [:id, :login, :name ....])
end
来自:here
其他链接:here
答案 3 :(得分:0)
渲染json时添加自定义json输出的最简单方法是使用提供许多json模板的gem-