Docs Menu
Docs Home
/ / /
PyMongo 드라이버
/

확장 JSON

JSON은 객체, 배열, 숫자, 문자열, 부울 및 null 값을 나타내는 데이터 형식입니다. 확장 JSON 형식은 '$' 접두사가 붙은 예약된 키 집합을 정의하여 MongoDB가 데이터를 저장하는 데 사용하는 형식인 BSON의 각 유형에 직접적으로 대응하는 필드 유형 정보를 표현합니다.

MongoDB 확장 JSON은 BSON 데이터를 표현하는 다양한 문자열 형식을 제공합니다. 각기 다른 형식은 JSON RFC를 준수하며 특정 사용 사례를 충족합니다. 표준(canonical) 형식이라고도 하는 확장(extended) 형식은 정보 손실 없는 양방향 변환을 위해 모든 BSON 유형에 대해 특정 표현을 제공합니다. 릴렉스(Relaxed) 모드 형식은 더 간결하고 일반 JSON에 가깝지만 숫자 필드의 특정 바이트 크기 등 모든 유형 정보를 나타내지는 않습니다.

각 형식에 대한 설명을 보려면 다음 표를 참조하세요.

이름
설명

확장

Also known as the canonical format, this JSON representation avoids loss of BSON type information.
This format prioritizes type preservation at the loss of human-readability and interoperability with older formats.

완화 모드

JSON representation that describes BSON documents with some type information loss.
This format prioritizes human-readability and interoperability at the loss of certain type information.

Shell

JSON representation that matches the syntax used in the MongoDB shell.
This format prioritizes compatibility with the MongoDB shell, which often uses JavaScript functions to represent types.

엄격한

Deprecated. This representation is the legacy format that fully conforms to the JSON RFC which allows any JSON parser to read the type information.

참고

드라이버는 $uuid 에서 확장 JSON 유형을 바이너리 string BsonBinary 하위 유형 의 4 객체로 구문 분석합니다. $uuid 필드 구문 분석에 대한 자세한 내용은 $uuid 필드 구문 분석을 위한 특별 규칙을 JSON 참조하세요. 섹션을 참조 .

JSON, BSON 및 확장 JSON 에 대해 자세히 학습 MongoDB Server 매뉴얼에서 JSON 및 BSON확장 JSON 에 대한 문서를 참조하세요.

다음 예시에서는 각 확장 JSON 형식으로 표시되는 ObjectId, 날짜, 긴 숫자 필드가 포함된 문서를 보여 줍니다. 원하는 형식의 예시 탭을 클릭합니다.

{
"_id": { "$oid": "573a1391f29313caabcd9637" },
"createdAt": { "$date": { "$numberLong": "1601499609" }},
"numViews": { "$numberLong": "36520312" }
}
{
"_id": { "$oid": "573a1391f29313caabcd9637" },
"createdAt": { "$date": "2020-09-30T18:22:51.648Z" },
"numViews": 36520312
}
{
"_id": ObjectId("573a1391f29313caabcd9637"),
"createdAt": ISODate("2020-09-30T18:22:51.648Z"),
"numViews": NumberLong("36520312")
}
{
"_id": { "$oid": "573a1391f29313caabcd9637" },
"createdAt": { "$date": 1601499609 },
"numViews": { "$numberLong": "36520312" }
}

bson.json_util.loads() 메서드를 호출하여 확장 JSON 문자열을 Python 객체 로 읽을 수 있습니다. 이 메서드는 확장 JSON 문자열을 구문 분석하고 데이터가 포함된 Python 목록을 반환합니다.

다음 예시 loads() 메서드를 사용하여 확장 JSON 문자열을 사전 목록으로 읽는 방법을 보여줍니다.

from bson.json_util import loads
ejson_str = '''[
{"foo": [1, 2]},
{"bar": {"hello": "world"}},
{"code": {
"$scope": {},
"$code": "function x() { return 1; }"
}},
{"bin": {
"$type": "80",
"$binary": "AQIDBA=="
}}
]'''
doc = loads(ejson_str)
print(doc)
[
{'foo': [1, 2]},
{'bar': {'hello': 'world'}},
{'code': Code('function x() { return 1; }', {})},
{'bin': Binary(b'\x01\x02\x03\x04', 128)}
]

Python 3에서 운전자 하위 유형이 0 인 JSON 바이너리 값을 bytes 클래스의 인스턴스로 디코딩합니다. Python 2에서 운전자 이러한 값을 하위 유형 0인 Binary 클래스의 인스턴스로 디코딩합니다.

다음 코드 예시는 PyMongo 하위 유형이 0인 JSON 바이너리 인스턴스를 디코딩하는 방법을 보여줍니다. Python 2 또는 Python 3 탭 선택하여 해당 코드를 확인합니다.

from bson.json_util import loads
doc = loads('{"b": {"$binary': b'this is a byte string'})
print(doc)
{u'b': Binary('this is a byte string', 0)}
from bson.json_util import loads
doc = loads('{"b": {"$binary': b'this is a byte string'})
print(doc)
{'b': b'this is a byte string'}

bson.json_util.dumps() 메서드를 호출하여 사전 목록에서 확장 JSON 문자열을 쓰기 (write) 수 있습니다. 다음 예시 확장 JSON 문자열을 완화된 형식으로 출력합니다.

from bson import Code, Binary
from bson.json_util import dumps
doc = [
{'foo': [1, 2]},
{'bar': {'hello': 'world'}},
{'code': Code('function x() { return 1; }', {})},
{'bin': Binary(b'\x01\x02\x03\x04', 128)}
]
ejson_str = dumps(doc)
print(ejson_str)
'''[
{"foo": [1, 2]},
{"bar": {"hello": "world"}},
{"code": {
"$code": "function x() { return 1; }",
"$scope": {}
}},
{"bin": {
"$binary": {
"base64": "AQIDBA==",
"subType": "80"
}}}
]'''

기본값 으로 dumps() 메서드는 확장 JSON 문자열을 완화된 형식으로 반환합니다. 다른 형식을 지정하려면 json_options 매개변수에 다음 값 중 하나를 전달합니다.

  • CANONICAL_JSON_OPTIONS: 확장 JSON 문자열을 표준 형식으로 반환합니다.

  • LEGACY_JSON_OPTIONS: 확장 JSON 문자열을 레거시 형식으로 반환합니다. 대신 Relaxed 또는 Canonical 형식을 사용하는 것이 좋습니다.

다음 예시 확장 JSON 표준 형식으로 출력하는 방법을 보여줍니다.

from bson import Code, Binary
from bson.json_util import dumps, CANONICAL_JSON_OPTIONS
doc = [
{'foo': [1, 2]},
{'bar': {'hello': 'world'}},
{'code': Code('function x() { return 1; }', {})},
{'bin': Binary(b'\x01\x02\x03\x04', 128)}
]
ejson_str = dumps(doc, json_options=CANONICAL_JSON_OPTIONS)
print(ejson_str)
'''[
{"foo": [
{"$numberInt": "1"},
{"$numberInt": "2"}
]},
{"bar": {"hello": "world"}},
{"code": {
"$code": "function x() { return 1; }",
"$scope": {}
}},
{"bin": {
"$binary": {
"base64": "AQIDBA==",
"subType": "80"
}}}
]'''

다음 섹션의 리소스는 확장 JSON 작업에 대한 자세한 정보를 제공합니다.

bson.json_util의 메서드 및 유형에 대한 자세한 내용은 다음 API 문서를 참조하세요.

python-bsonjs는 libbson을 기반으로 구축된 또 다른 패키지 로, BSON 확장 JSON 으로 변환할 수 있습니다. python-bsonjs 패키지 PyMongo 에 의존하지 않으며, 특정 경우에 json_util 보다 성능 향상을 제공할 수 있습니다.

RawBSONDocument 유형 사용

python-bsonjs RawBSONDocument 유형에서 변환할 때 PyMongo 와 가장 잘 작동합니다.

돌아가기

BSON

이 페이지의 내용

  • 개요
  • 확장 JSON 형식
  • 확장 JSON 예시
  • 확장 JSON 읽기
  • Python 2에서 이진 값 읽기
  • 확장 JSON 쓰기
  • 추가 정보
  • API 문서
  • 기타 패키지