Ruby data structure to display specific JSON format
[
{
"id":"123",
"name":"House"
},
{
"id":"1456",
"name":"Desperate Housewives"
},
{
"id":"789",
"name":"Dollhouse"
},
{
"id":"10",
"name":"Full House"
}
]
How can I render to generate this JSON format from Ruby? I have all the data from a DB (@result) and don't know what data structure to use in Ruby that will display this when I do this:
respond_to do |format|
format.json { render :json => @result}
end
What data structure should @result be and how can I execute it? Thanks!
a source to share
If @result
is an array of ActiveRecord model instances, it render :json => @result
will create something like what you need, but will include all the model attributes ( render
calls to_json
on the object you pass to it if it's not a string).
To only include the id and name attributes, you can use the parameter :only
to_json
:
respond_to do |format|
format.json { render :json => @result.to_json(:only => [:id, :name] }
end
Alternatively, you can create an array of Hash objects that only contain the required attributes:
respond_to do |format|
format.json { render :json =>
@result.collect {|o| {:id => o.id, :name => o.name} } }
end
Edit: See @ dt's comment below. A text model has an attribute that should be rendered as a name. This can be done by creating an alias for the text in the model:
class Model < ActiveRecord::Base
alias_method :name, :text
and including the name with :methods
:
respond_to do |format|
format.json { render :json => @result.to_json(:only => :id, :methods => :name }
end
Alternatively, the hash array can be used to rename the attribute:
respond_to do |format|
format.json { render :json =>
@result.collect {|o| {:id => o.id, :name => o.text} } }
end
a source to share
To create a JSON object of this particular format, you will need a ruby array containing the hashes for its elements.
@result = [{:id => "10", :name => "Full House"}, {:id => "789", :name => "blahblah"},...]
Rails converts the ruby array to json correctly in the render response block:
respond_to do |format|
format.json { render :json => @result}
end
a source to share
I used the jQuery plugin (FCBKComplete), which needed json results with specific key names, specifically "caption" and "value", which were not in the array I was calling to_json
on.
So I did this (hacked but it works):
render :json => taggings.map { |t| {:caption => t.tag.name, :value => t.tag.name} }.to_json
Where taggings
is the array returned by the ActiveRecord lookup and returns json like so:
[{"value":"tag.a","caption":"tag.a"},{"value":"tag.b","caption":"tag.b"}]
a source to share