Donald
Donald

Reputation: 233

Rails 3: Create a valid JSON Object from an Array of data

I am taking information from my MongoDB database (@bs). @bs has tons of information that I'm not interested, so what I need is to cycle trough all the information and create a new object with the information I need.

For that, I created a new array (@final) and I'm getting information and adding it to @final. The information seems to be getting there, however, when I convert it to JSON it's not a valid JSON object. What I intend to create in @final.json is this:

{ Something: [ {Email: "[email protected]", At: "date", ....}, {...}, ....] }

But when I do to_json I get [["At: date","Email: [email protected]","Message-id: .....

   @bs = coll.find("headers.from" => email, "date" => {"$gte" => initial_date, "$lte" => Time.now.utc})

@bs = @bs.to_a.map { |obj| obj.delete("completo"); obj.delete("_id"); obj.delete("date"); obj.delete("headers" => "content_type"); obj }

@final = Array.new

@bs.each do |a|
  elem = Array.new
  elem << "At: #{a["date"]}"
  elem << "Email: #{a["headers"]["to"]}"
  elem << "Message: #{a["headers"]["message_id"]}"
  elem << "Type: #{a["headers"]["status"]}"
  @final << elem
end

puts @final  
@final = @final.to_json
puts @final["Email"]     

Please help.

Thanks

Upvotes: 2

Views: 3276

Answers (1)

Douglas F Shearer
Douglas F Shearer

Reputation: 26528

In your loop, create a hash rather than an array. to_json should make this a JSON Object.

@bs.each do |a|
  @final << { :At => a['date'], :Email => a['headers']['to'], :Message => a['headers']['message_id'], :Type => a['headers']['status'] }
end

Upvotes: 1

Related Questions