Skip to content

Commit 17901af

Browse files
committed
gh-86018 Inconsistent errors for JSON-encoding NaNs with allow_nan=False
Fix issue where json.dumps provided a different error message than json.dump with non-finite values
1 parent ede6cb2 commit 17901af

File tree

3 files changed

+21
-15
lines changed

3 files changed

+21
-15
lines changed

Lib/test/test_json/test_float.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,9 @@ def test_allow_nan(self):
2626
res = self.loads(out)
2727
self.assertEqual(len(res), 1)
2828
self.assertNotEqual(res[0], res[0])
29-
self.assertRaises(ValueError, self.dumps, [val], allow_nan=False)
30-
29+
self.assertRaisesRegex(
30+
ValueError, str(val), self.dumps, [val], allow_nan=False
31+
)
3132

3233
class TestPyFloat(TestFloat, PyTest): pass
3334
class TestCFloat(TestFloat, CTest): pass
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
+ Fix issue where the error messages for :func:`json.dump` and :func:`json.dumps` were inconsistent when serializing non-finite values with ``allow_nan=False``

Modules/_json.c

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1324,21 +1324,25 @@ encoder_encode_float(PyEncoderObject *s, PyObject *obj)
13241324
/* Return the JSON representation of a PyFloat. */
13251325
double i = PyFloat_AS_DOUBLE(obj);
13261326
if (!Py_IS_FINITE(i)) {
1327-
if (!s->allow_nan) {
1328-
PyErr_SetString(
1329-
PyExc_ValueError,
1330-
"Out of range float values are not JSON compliant"
1331-
);
1332-
return NULL;
1333-
}
1327+
char* value;
1328+
char *py_value;
13341329
if (i > 0) {
1335-
return PyUnicode_FromString("Infinity");
1336-
}
1337-
else if (i < 0) {
1338-
return PyUnicode_FromString("-Infinity");
1330+
value = "Infinity";
1331+
py_value = "inf";
1332+
} else if (i < 0) {
1333+
value = "-Infinity";
1334+
py_value = "-inf";
1335+
} else {
1336+
value = "NaN";
1337+
py_value = "nan";
13391338
}
1340-
else {
1341-
return PyUnicode_FromString("NaN");
1339+
1340+
if (!s->allow_nan) {
1341+
char message[55] = "Out of range float values are not JSON compliant: ";
1342+
PyErr_SetString(PyExc_ValueError, strcat(message, py_value));
1343+
return NULL;
1344+
} else {
1345+
return PyUnicode_FromString(value);
13421346
}
13431347
}
13441348
return PyFloat_Type.tp_repr(obj);

0 commit comments

Comments
 (0)