Skip to content

Commit a70b494

Browse files
Backport PR #47431 on branch 1.4.x (Fix segmentation fault when JSON serializing a PeriodIndex) (#47457)
Backport PR #47431: Fix segmentation fault when JSON serializing a PeriodIndex Co-authored-by: Robert de Vries <[email protected]>
1 parent 2d370af commit a70b494

File tree

3 files changed

+11
-1
lines changed

3 files changed

+11
-1
lines changed

doc/source/whatsnew/v1.4.3.rst

+1
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ Fixed regressions
3030
- Fixed regression in :func:`assert_index_equal` when ``check_order=False`` and :class:`Index` has extension or object dtype (:issue:`47207`)
3131
- Fixed regression in :func:`read_excel` returning ints as floats on certain input sheets (:issue:`46988`)
3232
- Fixed regression in :meth:`DataFrame.shift` when ``axis`` is ``columns`` and ``fill_value`` is absent, ``freq`` is ignored (:issue:`47039`)
33+
- Fixed regression in :meth:`DataFrame.to_json` causing a segmentation violation when :class:`DataFrame` is created with an ``index`` parameter of the type :class:`PeriodIndex` (:issue:`46683`)
3334

3435
.. ---------------------------------------------------------------------------
3536

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

+3-1
Original file line numberDiff line numberDiff line change
@@ -228,8 +228,10 @@ static PyObject *get_values(PyObject *obj) {
228228
PyErr_Clear();
229229
} else if (PyObject_HasAttrString(values, "__array__")) {
230230
// We may have gotten a Categorical or Sparse array so call np.array
231+
PyObject *array_values = PyObject_CallMethod(values, "__array__",
232+
NULL);
231233
Py_DECREF(values);
232-
values = PyObject_CallMethod(values, "__array__", NULL);
234+
values = array_values;
233235
} else if (!PyArray_CheckExact(values)) {
234236
// Didn't get a numpy array, so keep trying
235237
Py_DECREF(values);

pandas/tests/io/json/test_ujson.py

+7
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
DatetimeIndex,
2525
Index,
2626
NaT,
27+
PeriodIndex,
2728
Series,
2829
Timedelta,
2930
Timestamp,
@@ -1242,3 +1243,9 @@ def test_encode_timedelta_iso(self, td):
12421243
expected = f'"{td.isoformat()}"'
12431244

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

0 commit comments

Comments
 (0)