Matt Elhotiby
Matt Elhotiby

Reputation: 44086

Formatting in ruby

I have this:

artists = search_object.map{|x| x["artistName"]}.uniq
=> ["Metallica", "Madonna", "Lady Gaga"]

I need it 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?

Upvotes: 0

Views: 103

Answers (1)

tokland
tokland

Reputation: 67900

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.

Upvotes: 8

Related Questions