Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-86018 Inconsistent errors for JSON-encoding NaNs with allow_nan=False #99172

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions Lib/test/test_json/test_float.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,9 @@ def test_allow_nan(self):
res = self.loads(out)
self.assertEqual(len(res), 1)
self.assertNotEqual(res[0], res[0])
self.assertRaises(ValueError, self.dumps, [val], allow_nan=False)

self.assertRaisesRegex(
ValueError, str(val), self.dumps, [val], allow_nan=False
)

class TestPyFloat(TestFloat, PyTest): pass
class TestCFloat(TestFloat, CTest): pass
Original file line number Diff line number Diff line change
@@ -0,0 +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``
30 changes: 17 additions & 13 deletions Modules/_json.c
Original file line number Diff line number Diff line change
Expand Up @@ -1324,21 +1324,25 @@ encoder_encode_float(PyEncoderObject *s, PyObject *obj)
/* Return the JSON representation of a PyFloat. */
double i = PyFloat_AS_DOUBLE(obj);
if (!Py_IS_FINITE(i)) {
if (!s->allow_nan) {
PyErr_SetString(
PyExc_ValueError,
"Out of range float values are not JSON compliant"
);
return NULL;
}
char* value;
char *py_value;
if (i > 0) {
return PyUnicode_FromString("Infinity");
}
else if (i < 0) {
return PyUnicode_FromString("-Infinity");
value = "Infinity";
py_value = "inf";
} else if (i < 0) {
value = "-Infinity";
py_value = "-inf";
} else {
value = "NaN";
py_value = "nan";
}
else {
return PyUnicode_FromString("NaN");

if (!s->allow_nan) {
char message[55] = "Out of range float values are not JSON compliant: ";
PyErr_SetString(PyExc_ValueError, strcat(message, py_value));
return NULL;
} else {
return PyUnicode_FromString(value);
}
}
return PyFloat_Type.tp_repr(obj);
Expand Down