Rails 3:从数据数组创建有效的 JSON 对象
我正在从 MongoDB 数据库 (@bs
) 获取信息。 @bs
有大量我不感兴趣的信息,所以我需要的是循环遍历所有信息并使用我需要的信息创建一个新对象。
为此,我创建了一个新数组 (@final
),并获取信息并将其添加到 @final 中。信息似乎已经到达那里,但是,当我将其转换为 JSON 时,它不是有效的 JSON 对象。我打算在 @final.json
中创建的是这样的:
{ Something: [ {Email: "[email protected]", At: "date", ....}, {...}, ....] }
但是当我执行 to_json 时,我得到 [["At: date","Email: [电子邮件受保护]","消息 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"]
请帮忙,
谢谢。
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在循环中,创建哈希而不是数组。
to_json
应该使其成为 JSON 对象。In your loop, create a hash rather than an array.
to_json
should make this a JSON Object.