漂亮的BSON :: OrderedHash使用Rails

时间:2013-06-12 18:05:00

标签: ruby-on-rails json mongodb bson

如果我将BSON::OrderedHash(来自MongoDb集合)传递给JSON.pretty_generate,我会收到json文档但未格式化。如何获得格式化为.pretty()的bson文档?

1 个答案:

答案 0 :(得分:1)

对于我来说,mongo 1.9.1,bson 1.9.1和json 1.8.0对我有用,如下面的测试代码所示,尽可能接近。

pretty_bson.rb

require 'mongo'
require 'bson'
require 'json'
require 'test/unit'

class BsonPrettyTest < Test::Unit::TestCase
  def setup
    @client = Mongo::MongoClient.new
    @db = @client['test']
    @coll = @db['people']
    @coll.remove
    assert_equal 0, @coll.count
  end

  test "bson pretty" do
    text = <<-EOF
{
    "firstName": "John",
    "lastName": "Smith",
    "age": 25,
    "address": {
    "streetAddress": "21 2nd Street",
    "city": "New York",
    "state": "NY",
    "postalCode": 10021
},
    "phoneNumbers": [
    {
        "type": "home",
    "number": "212 555-1234"
},
    {
        "type": "fax",
    "number": "646 555-4567"
}
]
}
    EOF
    hash = JSON.parse(text)
    @coll.insert(hash)
    doc = @coll.find_one
    assert_equal BSON::OrderedHash, doc.class
    puts JSON.pretty_generate(hash)
    puts JSON.pretty_generate(doc)
  end
end

ruby​​ pretty_bson.rb

Loaded suite pretty_bson
Started
{
  "firstName": "John",
  "lastName": "Smith",
  "age": 25,
  "address": {
    "streetAddress": "21 2nd Street",
    "city": "New York",
    "state": "NY",
    "postalCode": 10021
  },
  "phoneNumbers": [
    {
      "type": "home",
      "number": "212 555-1234"
    },
    {
      "type": "fax",
      "number": "646 555-4567"
    }
  ],
  "_id": {"$oid": "51df0c537f11bab55d000001"}
}
{
  "_id": {"$oid": "51df0c537f11bab55d000001"},
  "firstName": "John",
  "lastName": "Smith",
  "age": 25,
  "address": {
    "streetAddress": "21 2nd Street",
    "city": "New York",
    "state": "NY",
    "postalCode": 10021
  },
  "phoneNumbers": [
    {
      "type": "home",
      "number": "212 555-1234"
    },
    {
      "type": "fax",
      "number": "646 555-4567"
    }
  ]
}
.

Finished in 0.005689 seconds.

1 tests, 2 assertions, 0 failures, 0 errors, 0 pendings, 0 omissions, 0 notifications
100% passed

175.78 tests/s, 351.56 assertions/s