Trying to construct a comma delimited list from an array
So i need this format json and i have this so far
{
 query:'Li',
 suggestions:['Liberia','Libyan Arab','Liechtenstein','Lithuania'],
 data:['LR','LY','LI','LT']
}
 query = params[:query]
 artists = search_object.map{|x| x["artistName"]}
 @all_instances_hash = {}
 @all_instances_hash[:query] = query
  for instance in artists
    @all_instances_hash[:suggestions] = instance
  end
 respond_to do |format|
   format.json { render :json => @all_instances_hash}
 end
I have this code that i am using to try to make this format:
- query comes in from the params which is fine
- artists is an array of all the artist names, which is also good
- creating a hash 开发者_如何学编程to put the values in
- looping through the array of names and trying to put it in the hash under suggestions
- the problem is the line with suggestions, seems to be only saving the last one
this is my json and it seems to only be saving the last one
{"query":"James jones","suggestions":"James Brown & The James Brown Orchestra"}
Do
@all_instances_hash[:suggestions] = artists 
instead of
  for instance in artists
    @all_instances_hash[:suggestions] = instance
  end
In first case, you assign array to particular hash field. In second - you repeatedly assign different strings to that hash field.
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论