Skip to content

Commit 04425d4

Browse files
Fix segmentation fault when JSON serializing a PeriodIndex
Fixes pandas-dev#46683
1 parent f6eacb4 commit 04425d4

File tree

2 files changed

+9
-1
lines changed

2 files changed

+9
-1
lines changed

pandas/_libs/src/ujson/python/objToJSON.c

+2-1
Original file line numberDiff line numberDiff line change
@@ -238,8 +238,9 @@ static PyObject *get_values(PyObject *obj) {
238238
PyErr_Clear();
239239
} else if (PyObject_HasAttrString(values, "__array__")) {
240240
// We may have gotten a Categorical or Sparse array so call np.array
241+
PyObject *array_values = PyObject_CallMethod(values, "__array__", NULL);
241242
Py_DECREF(values);
242-
values = PyObject_CallMethod(values, "__array__", NULL);
243+
values = array_values;
243244
} else if (!PyArray_CheckExact(values)) {
244245
// Didn't get a numpy array, so keep trying
245246
Py_DECREF(values);

pandas/tests/io/json/test_ujson.py

+7
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
DatetimeIndex,
2424
Index,
2525
NaT,
26+
PeriodIndex,
2627
Series,
2728
Timedelta,
2829
Timestamp,
@@ -1240,3 +1241,9 @@ def test_encode_timedelta_iso(self, td):
12401241
expected = f'"{td.isoformat()}"'
12411242

12421243
assert result == expected
1244+
1245+
def test_encode_periodindex(self):
1246+
# GH 46683
1247+
p = PeriodIndex(["2022-04-06", "2022-04-07"], freq="D")
1248+
df = DataFrame(index=p)
1249+
assert df.to_json() == "{}"

0 commit comments

Comments
 (0)