Skip to content

Commit 167bfe2

Browse files
committed
Add numpy.dtypes type check in to_json function
1 parent dc8401a commit 167bfe2

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

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

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ int object_is_series_type(PyObject *obj);
6262
int object_is_index_type(PyObject *obj);
6363
int object_is_nat_type(PyObject *obj);
6464
int object_is_na_type(PyObject *obj);
65+
int object_is_ndtypes_type(PyObject *obj);
6566

6667
typedef struct __NpyArrContext {
6768
PyObject *array;
@@ -396,6 +397,24 @@ static const char *PyDecimalToUTF8Callback(JSOBJ _obj, JSONTypeContext *tc,
396397
return outValue;
397398
}
398399

400+
static const char *PyNpyDtypesToUTF8Callback(JSOBJ _obj, JSONTypeContext *tc,
401+
size_t *len) {
402+
PyObject *obj = (PyObject *)_obj;
403+
PyObject *str = PyObject_Str(obj);
404+
405+
if (str == NULL) {
406+
((JSONObjectEncoder *)tc->encoder)->errorMsg = "";
407+
return NULL;
408+
}
409+
410+
Py_ssize_t s_len;
411+
char *outValue = (char *)PyUnicode_AsUTF8AndSize(str, &s_len);
412+
*len = s_len;
413+
Py_DECREF(str);
414+
415+
return outValue;
416+
}
417+
399418
//=============================================================================
400419
// Numpy array iteration functions
401420
//=============================================================================
@@ -1583,6 +1602,10 @@ static void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) {
15831602
} else if (object_is_na_type(obj)) {
15841603
tc->type = JT_NULL;
15851604
return;
1605+
} else if (object_is_ndtypes_type(obj)) {
1606+
tc->type = JT_UTF8;
1607+
pc->PyTypeToUTF8 = PyNpyDtypesToUTF8Callback;
1608+
return;
15861609
}
15871610

15881611
ISITERABLE:

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

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,16 @@ int object_is_na_type(PyObject *obj) {
211211
}
212212
return result;
213213
}
214+
215+
int object_is_ndtypes_type(PyObject * obj){
216+
PyObject * ndtype = (PyObject*)&PyArrayDescr_Type;
217+
int result = PyObject_IsInstance(obj, ndtype);
218+
if (result == -1) {
219+
PyErr_Clear();
220+
return 0;
221+
}
222+
return result;
223+
}
214224
#else
215225
/* Used in objToJSON.c */
216226
int object_is_decimal_type(PyObject *obj) {

0 commit comments

Comments
 (0)