2013-06-12 2 views
0

Если я передаю BSON::OrderedHash (из коллекции MongoDb) в JSON.pretty_generate Я получаю json-документ, но неформатирован. Как я могу получить документ bson, отформатированный как .pretty()?Pretty BSON :: OrderedHash using Rails

ответ

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 

рубин 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 
Смежные вопросы