Fix ObjectId serialization with comprehensive recursive conversion - Handle all ObjectId fields in nested structures and datetime objects
Browse files
app.py
CHANGED
|
@@ -305,27 +305,27 @@ def serialize_checklist(checklist_doc: Dict[str, Any]) -> Dict[str, Any]:
|
|
| 305 |
Dictionary with ObjectId converted to string
|
| 306 |
"""
|
| 307 |
import copy
|
|
|
|
|
|
|
| 308 |
|
| 309 |
# Make a deep copy to avoid modifying the original document
|
| 310 |
serialized = copy.deepcopy(checklist_doc)
|
| 311 |
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
|
|
|
|
|
|
|
|
|
| 321 |
|
| 322 |
-
#
|
| 323 |
-
|
| 324 |
-
for item in section.get('items', []):
|
| 325 |
-
if 'checkedAt' in item and item['checkedAt']:
|
| 326 |
-
# Only convert if it's a datetime object, not a string
|
| 327 |
-
if hasattr(item['checkedAt'], 'isoformat'):
|
| 328 |
-
item['checkedAt'] = item['checkedAt'].isoformat()
|
| 329 |
|
| 330 |
return serialized
|
| 331 |
|
|
|
|
| 305 |
Dictionary with ObjectId converted to string
|
| 306 |
"""
|
| 307 |
import copy
|
| 308 |
+
import json
|
| 309 |
+
from bson import ObjectId
|
| 310 |
|
| 311 |
# Make a deep copy to avoid modifying the original document
|
| 312 |
serialized = copy.deepcopy(checklist_doc)
|
| 313 |
|
| 314 |
+
# Convert ObjectId to string recursively
|
| 315 |
+
def convert_objectid(obj):
|
| 316 |
+
if isinstance(obj, ObjectId):
|
| 317 |
+
return str(obj)
|
| 318 |
+
elif isinstance(obj, dict):
|
| 319 |
+
return {key: convert_objectid(value) for key, value in obj.items()}
|
| 320 |
+
elif isinstance(obj, list):
|
| 321 |
+
return [convert_objectid(item) for item in obj]
|
| 322 |
+
elif hasattr(obj, 'isoformat'): # datetime objects
|
| 323 |
+
return obj.isoformat()
|
| 324 |
+
else:
|
| 325 |
+
return obj
|
| 326 |
|
| 327 |
+
# Apply ObjectId conversion to the entire document
|
| 328 |
+
serialized = convert_objectid(serialized)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 329 |
|
| 330 |
return serialized
|
| 331 |
|