Added default JSON encoder to serialize date and datetime objects
authorThierry Florac <thierry.florac@onf.fr>
Mon, 17 Sep 2018 16:14:22 +0200
changeset 227 52a03aa1cf9d
parent 226 830d5222e806
child 228 1edcd4c94110
Added default JSON encoder to serialize date and datetime objects
src/pyams_utils/json.py
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/pyams_utils/json.py	Mon Sep 17 16:14:22 2018 +0200
@@ -0,0 +1,39 @@
+#
+# Copyright (c) 2008-2018 Thierry Florac <tflorac AT ulthar.net>
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+
+__docformat__ = 'restructuredtext'
+
+
+# import standard library
+import json
+
+from datetime import date, datetime
+
+# import interfaces
+
+# import packages
+
+
+def default_json_encoder(obj):
+    if isinstance(obj, (date, datetime)):
+        return obj.isoformat()
+    else:
+        return obj
+
+
+json._default_encoder = json.JSONEncoder(skipkeys=False,
+                                         ensure_ascii=True,
+                                         check_circular=True,
+                                         allow_nan=True,
+                                         indent=None,
+                                         separators=None,
+                                         default=default_json_encoder)