0

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

4

1 回答 1

1

它适用于我的 mongo 1.9.1、bson 1.9.1 和 json 1.8.0,如以下测试代码所示,与预期的一样接近。

漂亮的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
于 2013-07-11T19:55:26.657 回答