Skip to content

Commit faacb72

Browse files
Fix segmentation fault when JSON serializing a PeriodIndex (#47431)
1 parent d40c371 commit faacb72

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
@@ -31,6 +31,7 @@ Fixed regressions
3131
- Fixed regression in :func:`assert_index_equal` when ``check_order=False`` and :class:`Index` has extension or object dtype (:issue:`47207`)
3232
- Fixed regression in :func:`read_excel` returning ints as floats on certain input sheets (:issue:`46988`)
3333
- Fixed regression in :meth:`DataFrame.shift` when ``axis`` is ``columns`` and ``fill_value`` is absent, ``freq`` is ignored (:issue:`47039`)
34+
- 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`)
3435

3536
.. ---------------------------------------------------------------------------
3637

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

+3-1
Original file line numberDiff line numberDiff line change
@@ -238,8 +238,10 @@ 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__",
242+
NULL);
241243
Py_DECREF(values);
242-
values = PyObject_CallMethod(values, "__array__", NULL);
244+
values = array_values;
243245
} else if (!PyArray_CheckExact(values)) {
244246
// Didn't get a numpy array, so keep trying
245247
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)