Skip to content

Commit a06816e

Browse files
gpoulinjreback
authored andcommitted
BUG: segfault on to_json serializing a 0d-ndarray, #9576
1 parent 8d4d04a commit a06816e

File tree

3 files changed

+25
-1
lines changed

3 files changed

+25
-1
lines changed

doc/source/whatsnew/v0.17.0.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -823,3 +823,4 @@ Bug Fixes
823823
- Bug in ``TimedeltaIndex`` formatter causing error while trying to save ``DataFrame`` with ``TimedeltaIndex`` using ``to_csv`` (:issue:`10833`)
824824
- Bug in ``DataFrame.where`` when handling Series slicing (:issue:`10218`, :issue:`9558`)
825825
- Bug where ``pd.read_gbq`` throws ``ValueError`` when Bigquery returns zero rows (:issue:`10273`)
826+
- Bug in ``to_json`` which was causing segmentation fault when serializing 0-rank ndarray (:issue:`9576`)

pandas/io/tests/test_json/test_ujson.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1035,6 +1035,12 @@ def testArrays(self):
10351035
outp = ujson.decode(ujson.encode(arr), numpy=True, dtype=np.float32)
10361036
assert_array_almost_equal_nulp(arr, outp)
10371037

1038+
def testOdArray(self):
1039+
def will_raise():
1040+
ujson.encode(np.array(1))
1041+
1042+
self.assertRaises(TypeError, will_raise)
1043+
10381044
def testArrayNumpyExcept(self):
10391045

10401046
input = ujson.dumps([42, {}, 'a'])

pandas/src/ujson/python/objToJSON.c

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1863,7 +1863,7 @@ void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc)
18631863
}
18641864
tc->prv = pc;
18651865

1866-
if (PyIter_Check(obj) || PyArray_Check(obj))
1866+
if (PyIter_Check(obj) || (PyArray_Check(obj) && !PyArray_CheckScalar(obj) ))
18671867
{
18681868
PRINTMARK();
18691869
goto ISITERABLE;
@@ -2065,6 +2065,23 @@ void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc)
20652065
pc->PyTypeToJSON = NpyFloatToDOUBLE; tc->type = JT_DOUBLE;
20662066
return;
20672067
}
2068+
else
2069+
if (PyArray_Check(obj) && PyArray_CheckScalar(obj)) {
2070+
#if PY_MAJOR_VERSION >= 3
2071+
PyErr_Format(
2072+
PyExc_TypeError,
2073+
"%R (0d array) is not JSON serializable at the moment",
2074+
obj
2075+
);
2076+
#else
2077+
PyErr_Format(
2078+
PyExc_TypeError,
2079+
"%s (0d array) is not JSON serializable at the moment",
2080+
PyString_AsString(PyObject_Repr(obj))
2081+
);
2082+
#endif
2083+
return;
2084+
}
20682085

20692086
ISITERABLE:
20702087

0 commit comments

Comments
 (0)