Skip to content

Commit f24e165

Browse files
PYTHON-2263 Respect UuidRepresentation.UNSPECIFIED when parsing $uuid fields in extended JSON (#464)
1 parent f80c824 commit f24e165

File tree

2 files changed

+11
-4
lines changed

2 files changed

+11
-4
lines changed

bson/json_util.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -449,7 +449,7 @@ def object_hook(dct, json_options=DEFAULT_JSON_OPTIONS):
449449
if "$code" in dct:
450450
return _parse_canonical_code(dct)
451451
if "$uuid" in dct:
452-
return _parse_legacy_uuid(dct)
452+
return _parse_legacy_uuid(dct, json_options)
453453
if "$undefined" in dct:
454454
return None
455455
if "$numberLong" in dct:
@@ -484,11 +484,14 @@ def _parse_legacy_regex(doc):
484484
return Regex(pattern, flags)
485485

486486

487-
def _parse_legacy_uuid(doc):
487+
def _parse_legacy_uuid(doc, json_options):
488488
"""Decode a JSON legacy $uuid to Python UUID."""
489489
if len(doc) != 1:
490490
raise TypeError('Bad $uuid, extra field(s): %s' % (doc,))
491-
return uuid.UUID(doc["$uuid"])
491+
if json_options.uuid_representation == UuidRepresentation.UNSPECIFIED:
492+
return Binary.from_uuid(uuid.UUID(doc["$uuid"]))
493+
else:
494+
return uuid.UUID(doc["$uuid"])
492495

493496

494497
def _binary_or_uuid(data, subtype, json_options):

test/test_json_util.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -301,7 +301,11 @@ def test_uuid_uuid_rep_unspecified(self):
301301
ext_json_str = json_util.dumps(doc)
302302
self.assertEqual(
303303
doc, json_util.loads(ext_json_str, json_options=options))
304-
304+
# $uuid-encoded fields
305+
doc = {'uuid': Binary(_uuid.bytes, subtype=4)}
306+
ext_json_str = json_util.dumps({'uuid': _uuid})
307+
self.assertEqual(
308+
doc, json_util.loads(ext_json_str, json_options=options))
305309

306310
def test_binary(self):
307311
if PY3:

0 commit comments

Comments
 (0)