开发者

Formatting in ruby

开发者 https://www.devze.com 2023-02-17 14:47 出处:网络
I have this: artists = search_object.map{|x| x[\"artistName\"]}.uniq => [\"Metallica\", \"Madonna\", \"Lady Gaga\"]

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消