Skip to content

Commit a1b08f0

Browse files
Ken Kurzweilmdirolf
authored andcommitted
Added uuid to json de/serialization
1 parent 3b9328c commit a1b08f0

File tree

2 files changed

+9
-0
lines changed

2 files changed

+9
-0
lines changed

pymongo/json_util.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@
5151
import calendar
5252
import datetime
5353
import re
54+
import uuid
5455

5556
from pymongo.dbref import DBRef
5657
from pymongo.max_key import MaxKey
@@ -89,6 +90,8 @@ def object_hook(dct):
8990
return MinKey()
9091
if "$maxKey" in dct:
9192
return MaxKey()
93+
if "$uuid" in dct:
94+
return uuid.UUID(dct["$uuid"])
9295
return dct
9396

9497

@@ -118,4 +121,6 @@ def default(obj):
118121
return {"$maxKey": 1}
119122
if isinstance(obj, Timestamp):
120123
return {"t": obj.time, "i": obj.inc}
124+
if isinstance(obj, uuid.UUID):
125+
return {"$uuid": obj.hex}
121126
raise TypeError("%r is not JSON serializable" % obj)

test/test_json_util.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
import datetime
1919
import re
2020
import sys
21+
import uuid
2122
json_lib = True
2223
try:
2324
import json
@@ -88,5 +89,8 @@ def test_timestamp(self):
8889
self.assertEqual(dct['ts']['t'], 4)
8990
self.assertEqual(dct['ts']['i'], 13)
9091

92+
def test_uuid(self):
93+
self.round_trip({'uuid' : uuid.UUID('f47ac10b-58cc-4372-a567-0e02b2c3d479')})
94+
9195
if __name__ == "__main__":
9296
unittest.main()

0 commit comments

Comments
 (0)