From a70b49476bf33a5cbc6fbbc2da343018dea884f9 Mon Sep 17 00:00:00 2001 From: MeeseeksMachine <39504233+meeseeksmachine@users.noreply.github.com> Date: Wed, 22 Jun 2022 06:07:32 -0500 Subject: [PATCH] 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 --- doc/source/whatsnew/v1.4.3.rst | 1 + pandas/_libs/src/ujson/python/objToJSON.c | 4 +++- pandas/tests/io/json/test_ujson.py | 7 +++++++ 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/doc/source/whatsnew/v1.4.3.rst b/doc/source/whatsnew/v1.4.3.rst index a4d81533df23d..4034655ccd325 100644 --- a/doc/source/whatsnew/v1.4.3.rst +++ b/doc/source/whatsnew/v1.4.3.rst @@ -30,6 +30,7 @@ Fixed regressions - Fixed regression in :func:`assert_index_equal` when ``check_order=False`` and :class:`Index` has extension or object dtype (:issue:`47207`) - Fixed regression in :func:`read_excel` returning ints as floats on certain input sheets (:issue:`46988`) - Fixed regression in :meth:`DataFrame.shift` when ``axis`` is ``columns`` and ``fill_value`` is absent, ``freq`` is ignored (:issue:`47039`) +- 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`) .. --------------------------------------------------------------------------- diff --git a/pandas/_libs/src/ujson/python/objToJSON.c b/pandas/_libs/src/ujson/python/objToJSON.c index c4609992342c3..5ad8029b38754 100644 --- a/pandas/_libs/src/ujson/python/objToJSON.c +++ b/pandas/_libs/src/ujson/python/objToJSON.c @@ -228,8 +228,10 @@ static PyObject *get_values(PyObject *obj) { PyErr_Clear(); } else if (PyObject_HasAttrString(values, "__array__")) { // We may have gotten a Categorical or Sparse array so call np.array + PyObject *array_values = PyObject_CallMethod(values, "__array__", + NULL); Py_DECREF(values); - values = PyObject_CallMethod(values, "__array__", NULL); + values = array_values; } else if (!PyArray_CheckExact(values)) { // Didn't get a numpy array, so keep trying Py_DECREF(values); diff --git a/pandas/tests/io/json/test_ujson.py b/pandas/tests/io/json/test_ujson.py index 41a417f6b3ef4..982d751692eb9 100644 --- a/pandas/tests/io/json/test_ujson.py +++ b/pandas/tests/io/json/test_ujson.py @@ -24,6 +24,7 @@ DatetimeIndex, Index, NaT, + PeriodIndex, Series, Timedelta, Timestamp, @@ -1242,3 +1243,9 @@ def test_encode_timedelta_iso(self, td): expected = f'"{td.isoformat()}"' assert result == expected + + def test_encode_periodindex(self): + # GH 46683 + p = PeriodIndex(["2022-04-06", "2022-04-07"], freq="D") + df = DataFrame(index=p) + assert df.to_json() == "{}"