拡張 JSON
項目一覧
Overview
JSON は、オブジェクト、配列、数値、string、ブール値、null の値を表すデータ形式です。 JSON$
BSON拡張 形式では、MongoDB がデータを保存するために使用する形式である の各型に直接対応するフィールド型情報を表すために、"{0 " というプレフィックスが付いたキーの予約セットが定義されます。
拡張 JSON 形式
MongoDB 拡張 JSON は、BSON データを表すためのさまざまな string 形式を機能します。 異なる形式はそれぞれ JSON RFC に準拠し、特定のユースケースを満たしています。 拡張形式は標準形式とも呼ばれますが、情報を失うことなく双方向変換を行うためにすべての BSON 型に特定の表現を備えています。 緩和モード形式は、より簡潔で通常の 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 からバイナリ サブタイプ4のBsonBinary
オブジェクトに解析します。 $uuid
フィールド解析の詳細については、 $uuid フィールドを解析するための特別なルール をJSON 参照してください セクションを参照して 。
JSON、 BSON、 拡張JSONの詳細については、 MongoDB ServerマニュアルのJSONとBSONと 拡張JSONに関する記事を参照してください。
拡張 JSON の例
次の例は、それぞれの拡張 JSON 形式で表される ObjectId、date、long 数値フィールドを含むドキュメントを示しています。 表示する例の形式に対応するタブをクリックします。
{ "_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" } }
拡張 JSON の読み取り
bson.json_util.loads()
メソッドを呼び出すと、拡張JSON string をPythonオブジェクトに読み込むことができます。このメソッドは、拡張JSON string を解析し、 データを含むPythonリストを返します。
次の例は、loads()
メソッドを使用して、拡張JSON string を辞書のリストに読み込む方法を示しています。
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でのバイナリ値の読み取り 2
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'}
拡張 JSON の書込み (write)
bson.json_util.dumps()
メソッドを呼び出すと、辞書のリストから拡張JSON string を書き込むことができます。次の例では、拡張JSON string を Relaxed形式で出力します。
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 string を返します。別の形式を指定するには、json_options
パラメータに次のいずれかの値を渡します。
CANONICAL_JSON_OPTIONS
: 拡張JSON string を 標準形式で返します。LEGACY_JSON_OPTIONS
: レガシー形式の拡張JSON string を返します。代わりに、緩和形式を使用することをお勧めします。
次の例は、拡張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 の操作の詳細を提供します。
API ドキュメント
bson.json_util
のメソッドとタイプの詳細については、次のAPIドキュメントを参照してください。
その他のパッケージ
python-bsonjs は、 libbson 上に構築された別のパッケージで、 BSON を拡張JSONに変換できます。python-bsonjs
パッケージはPyMongoに依存しておらず、場合によっては json_util
よりもパフォーマンスが向上する可能性があります。
Tip
RawBSONDocument 型の使用
python-bsonjs
は、RawBSONDocument
型から変換する場合、 PyMongoで最も動作します。