Skip to content

Commit 7af1abf

Browse files
authored
Merge pull request #7 from robabram/ra/date_to_str_fix
to_dict method should not auto convert date values to str.
2 parents 03f543a + 0a49123 commit 7af1abf

3 files changed

Lines changed: 22 additions & 2 deletions

File tree

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
from setuptools import setup, find_packages
88

9-
__VERSION__ = "1.0.6"
9+
__VERSION__ = "1.0.8"
1010

1111
base_dir = os.path.abspath(os.path.dirname(__file__))
1212

src/python_easy_json/json_object.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ def to_dict(self, recursive: bool = True, dates_to_str: bool = False):
138138
for k, v in self._clean_data().items():
139139
if isinstance(v, JSONObject) and recursive is True:
140140
data[k] = v.to_dict(recursive=recursive, dates_to_str=dates_to_str)
141-
elif isinstance(v, (datetime.datetime, datetime.date)):
141+
elif isinstance(v, (datetime.datetime, datetime.date)) and dates_to_str is True:
142142
data[k] = self._json_serial(v)
143143
elif isinstance(v, list):
144144
nl = list()

tests/test_object_model.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
# file 'LICENSE', which is part of this source code package.
44
#
55
from datetime import date, datetime
6+
from dateutil import parser as du_parser
7+
import json
68
from python_easy_json import JSONObject
79
from tests.base_test import BaseTestCase
810
from typing import List
@@ -159,3 +161,21 @@ def test_incomplete_cake_models(self):
159161
# are missing in this case.
160162
self.assertIsInstance(obj.topping[0].id, str)
161163
self.assertEqual(obj.topping[0].id, "5001")
164+
165+
def test_to_dict_datetime_conversion(self):
166+
""" Test that when using the "to_dict()" method that datetime values are handled correctly. """
167+
168+
input = json.loads(self.json_data.simple)
169+
input['field_date'] = du_parser.parse(input['field_date']).date()
170+
input['field_datetime'] = du_parser.parse(input['field_datetime'])
171+
172+
obj = SimpleModel(input)
173+
174+
# Test that date and datetime values are not converted to string
175+
data = obj.to_dict(dates_to_str=False)
176+
self.assertIsInstance(data['field_date'], date)
177+
self.assertIsInstance(data['field_datetime'], datetime)
178+
179+
data = obj.to_dict(dates_to_str=True)
180+
self.assertIsInstance(data['field_date'], str)
181+
self.assertIsInstance(data['field_datetime'], str)

0 commit comments

Comments
 (0)