如何在rails中自定义json输出?
我有一个语言模型,我希望将所有语言作为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,” 语言 “:” 西class牙语”, “的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, “语言”: “西class牙”, “的updated_at”:空},{ “created_at”日期null, “ID”:6, “语言”: “荷兰人”, “的updated_at”:空},{ “created_at”:空, “ID”:7, “语言”: “泰米尔语”, “的updated_at”:空}]}
更新
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
我相信这应该有效:
format.json { render json: { "language" => @languages.as_json(:root => false) }.to_json }
这样做是为了将@languages
数组转换为没有根密钥的JSON格式散列模型数组(使用as_json
),然后将结果包装在具有根密钥“language”的散列中,并将该散列转换为JSON带有to_json
字符串。 (有关使用as_json
包含或不包含根节点的详细信息,请参阅文档 。)
例如,使用模型Post
:
posts = Post.all #=> [#] # 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\"}]}"
我建议你使用rabl gem( https://github.com/nesquena/rabl )来格式化你的数据。
覆盖要自定义的模型上的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
来自: 这里
其他链接: 这里
渲染json时添加自定义json输出的最简单方法是使用提供许多json模板的gem-