Skip to content

Commit 0842957

Browse files
authored
[7.x] Serialize only 'pd.NA' to 'None'
1 parent 53de889 commit 0842957

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

elasticsearch/serializer.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ class JSONSerializer(object):
6767
mimetype = "application/json"
6868

6969
def default(self, data):
70-
if isinstance(data, TIME_TYPES):
70+
if isinstance(data, TIME_TYPES) and getattr(pd, "NaT", None) is not data:
7171
return data.isoformat()
7272
elif isinstance(data, uuid.UUID):
7373
return str(data)
@@ -87,7 +87,7 @@ def default(self, data):
8787
if pd:
8888
if isinstance(data, (pd.Series, pd.Categorical)):
8989
return data.tolist()
90-
elif hasattr(pd, "NA") and pd.isna(data):
90+
elif data is getattr(pd, "NA", None):
9191
return None
9292

9393
raise TypeError("Unable to serialize %r (type: %s)" % (data, type(data)))

test_elasticsearch/test_serializer.py

+10
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,11 @@ def test_serializes_numpy_ndarray(self):
9393
JSONSerializer().dumps({"d": np.zeros((2, 2), dtype=np.uint8)}),
9494
)
9595

96+
def test_serializes_numpy_nan_to_nan(self):
97+
self.assertEqual(
98+
'{"d":NaN}', JSONSerializer().dumps({"d": np.nan}),
99+
)
100+
96101
def test_serializes_pandas_timestamp(self):
97102
self.assertEqual(
98103
'{"d":"2010-10-01T02:30:00"}',
@@ -112,6 +117,11 @@ def test_serializes_pandas_na(self):
112117
'{"d":null}', JSONSerializer().dumps({"d": pd.NA}),
113118
)
114119

120+
def test_raises_serialization_error_pandas_nat(self):
121+
if not hasattr(pd, "NaT"):
122+
raise SkipTest("pandas.NaT required")
123+
self.assertRaises(SerializationError, JSONSerializer().dumps, {"d": pd.NaT})
124+
115125
def test_serializes_pandas_category(self):
116126
cat = pd.Categorical(["a", "c", "b", "a"], categories=["a", "b", "c"])
117127
self.assertEqual(

0 commit comments

Comments
 (0)