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: "[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

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks. I do that but then I Can't do @final = @final.to_json puts @final['Email'] -- It returns the string "Email"
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.
So after converting it to JSON, how do I do if I want to access the members of the document?
1.9.3p194 :001 > blah = Hash.new => {} 1.9.3p194 :002 > blah << {:something => "something"} NoMethodError: undefined method `<<' for {}:Hash
blah or @final is an array, as per the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.