2

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: "xxx@xxx.com", At: "date", ....}, {...}, ....] }

But when I do to_json I get [["At: date","Email: mail_test@tidgdfp.org","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

insumity
  • 5,311
  • 8
  • 36
  • 64
Donald
  • 243
  • 4
  • 10

1 Answers1

1

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
Douglas F Shearer
  • 25,952
  • 2
  • 48
  • 48
  • Thanks. I do that but then I Can't do @final = @final.to_json puts @final['Email'] -- It returns the string "Email" – Donald May 13 '11 at 11:09
  • After you convert the array to `json` you have a string. the `[]` operator on a string looks for a match in the string, which it finds. Even if @final was the array, you'd have to do something like `@final.first[:Email]` to get the email value for one of the array objects. – Douglas F Shearer May 13 '11 at 11:13
  • So after converting it to JSON, how do I do if I want to access the members of the document? – Donald May 13 '11 at 11:15
  • 1.9.3p194 :001 > blah = Hash.new => {} 1.9.3p194 :002 > blah << {:something => "something"} NoMethodError: undefined method `<<' for {}:Hash – botbot Feb 21 '13 at 00:18
  • blah or @final is an array, as per the question. – Douglas F Shearer Feb 21 '13 at 10:37