# HG changeset patch # User Fredrik Lundh # Date 1257464227 -3600 # Node ID c20be1d34e7eb5482f2e22041cabd750e60f8e52 # Parent 6973bfcf64bf829a33c6aa8d1ce5bb693ccab3de Use tp_str slot to stringify ints/longs/floats. diff -r 6973bfcf64bf829a33c6aa8d1ce5bb693ccab3de -r c20be1d34e7eb5482f2e22041cabd750e60f8e52 cjson.c --- a/cjson.c Thu Nov 05 22:59:40 2009 +0100 +++ b/cjson.c Fri Nov 06 00:37:07 2009 +0100 @@ -1171,6 +1171,8 @@ return encode_string_latin1(object); } else if (PyUnicode_Check(object)) { return encode_unicode(object); + } else if (PyInt_Check(object)) { + goto stringify; } else if (PyFloat_Check(object)) { double val = PyFloat_AS_DOUBLE(object); if (Py_IS_NAN(val)) { @@ -1181,11 +1183,10 @@ } else { return PyString_FromString("-Infinity"); } - } else { - return PyObject_Str(object); - } - } else if (PyInt_Check(object) || PyLong_Check(object)) { - return PyObject_Str(object); + } else + goto stringify; + } else if (PyLong_Check(object)) { + goto stringify; } else if (PyList_Check(object)) { return encode_list(encode, object); } else if (PyTuple_Check(object)) { @@ -1196,6 +1197,13 @@ PyErr_SetString(JSON_EncodeError, "object is not JSON encodable"); return NULL; } + +stringify: + /* PyObject_Str does a bunch of extra checks, so use the slot + directly if it's there. */ + if (object->ob_type->tp_str) + return (*object->ob_type->tp_str)(object); + return PyObject_Str(object); }