Formatting in ruby
I have this:
artists = search_object.map{|x| x["artistName"]}.uniq
=> ["Metallica", "Madonna", "Lady Gaga"]
I need i开发者_开发百科t in this format json:
{"artists":[{"name":"Metallica"},{"name":"Madonna"},{"name":"Lady Gaga"}]}
I tried this:
>> @api = {}
=> {}
>> @api[:artists] = artists
=> ["Metallica", "Madonna", "Lady Gaga"]
>> @api
=> {:artists=>["Metallica", "Madonna", "Lady Gaga"]}
I need it in an api call like this:
respond_to do |format|
format.json { render :json => @api}
end
But whats returned is not proper json.
How do I get it in this format?
A simple Enumerable#map
should do:
artists = ["Metallica", "Madonna", "Lady Gaga"]
@api = {:artists => artists.map { |artist| {:name => artist} }}
#=> {:artists=>[{:name=>"Metallica"}, {:name=>"Madonna"}, {:name=>"Lady Gaga"}]}
Note that you can use symbol as hash keys (it's more idiomatic) because they are converted to JSON as normal strings.
精彩评论