
MongoDBBSONDocument::fromJSON 메서드는 JSON 데이터를 MongoDB BSON 문서로 변환하는 데 사용됩니다. 그러나 JSON 데이터에 오류가 있는 경우 오류가 발생할 수 있습니다.
오류가 발생하는 이유는 JSON 데이터의 타입이 일치하지 않기 때문입니다. 예를 들어, "age" 필드는 숫자 타입이지만, JSON 데이터에서는 문자열 타입으로 지정되어 있습니다.
오류를 처리하는 방법은 다음과 같습니다.
1. JSON 데이터를 검증하는 코드를 추가하여 오류를 감지하고 처리할 수 있습니다.
#hostingforum.kr
ruby
require 'bson'
json_data = '{ "name": "John Doe", "age": "thirty", "address": { "street": "123 Main St", "city": "Anytown", "state": "CA", "zip": "12345" } }'
begin
bson_doc = BSON::Document.from_json(json_data)
puts bson_doc
rescue BSON::InvalidBSONError => e
puts "오류 발생: #{e.message}"
end
2. JSON 데이터를 파서하여 오류를 감지하고 처리할 수 있습니다.
#hostingforum.kr
ruby
require 'json'
json_data = '{ "name": "John Doe", "age": "thirty", "address": { "street": "123 Main St", "city": "Anytown", "state": "CA", "zip": "12345" } }'
begin
json_hash = JSON.parse(json_data)
if json_hash["age"].is_a?(String)
puts "오류 발생: age 필드는 숫자 타입이어야 합니다."
else
bson_doc = BSON::Document.from_json(json_data.to_json)
puts bson_doc
end
rescue JSON::ParserError => e
puts "오류 발생: #{e.message}"
end
이러한 방법을 사용하여 JSON 데이터의 오류를 감지하고 처리할 수 있습니다.
2025-08-11 07:20