From b618dc3b5ebdd5925855ea5183382c328170cfb9 Mon Sep 17 00:00:00 2001 From: Thejesh Date: Fri, 27 Nov 2026 05:40:26 -0800 Subject: [PATCH] gh-162525: Fix json C encoder for str subclass separators (#162526) (cherry picked from commit 551df9d7d6054dac9ce78a2f04d46113b1ef9650) --- Lib/test/test_json/test_separators.py | 15 +++++++++++++++ Lib/test/test_json/test_speedups.py | 14 ++++++++++++++ ...2026-11-24-04-43-08.gh-issue-162525.Me7bYD.rst | 3 +++ Modules/_json.c | 15 ++++++++++----- 4 files changed, 42 insertions(+), 5 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2026-11-24-04-43-08.gh-issue-162525.Me7bYD.rst diff --git a/Lib/test/test_json/test_separators.py b/Lib/test/test_json/test_separators.py index 8ca517405179e5..478988697dca17 100644 --- a/Lib/test/test_json/test_separators.py +++ b/Lib/test/test_json/test_separators.py @@ -45,6 +45,21 @@ def test_illegal_separators(self): self.assertRaises(TypeError, self.dumps, h, separators=(', ', b': ')) self.assertRaises(TypeError, self.dumps, h, separators=(b', ', b': ')) + def test_str_subclass_separators(self): + # Don't call obj.__str__() on str subclasses (see gh-148241) + class StrSubclass(str): + def __str__(self): + return "StrSubclass" + + h = {'a': [1, 2], 'b': 3} + seps = (StrSubclass(',_'), StrSubclass(':_')) + self.assertEqual(self.dumps(h, separators=seps), + '{"a":_[1,_2],_"b":_3}') + self.assertEqual(self.dumps(h, separators=seps, sort_keys=True), + '{"a":_[1,_2],_"b":_3}') + self.assertEqual(self.dumps(h, separators=seps, indent=1), + '{\n "a":_[\n 1,_\n 2\n ],_\n "b":_3\n}') + class TestPySeparators(TestSeparators, PyTest): pass class TestCSeparators(TestSeparators, CTest): pass diff --git a/Lib/test/test_json/test_speedups.py b/Lib/test/test_json/test_speedups.py index 0b22a0bf4b9538..0d2189d65f128a 100644 --- a/Lib/test/test_json/test_speedups.py +++ b/Lib/test/test_json/test_speedups.py @@ -60,6 +60,20 @@ def bad_encoder2(*args): with self.assertRaises(ZeroDivisionError): enc('spam', 4) + def test_str_subclass_from_encoder(self): + # gh-162525: Don't call __str__() on a str subclass returned by + # the encoder() argument + class StrSubclass(str): + def __str__(self): + return "StrSubclass" + + enc = self.json.encoder.c_make_encoder(None, lambda obj: str(obj), + lambda s: StrSubclass('"x"'), + None, ': ', ', ', + False, False, False) + self.assertEqual(enc('spam', 0), ('"x"',)) + self.assertEqual(enc({'spam': 'eggs'}, 0), ('{"x": "x"}',)) + def test_bad_markers_argument_to_encoder(self): # https://bugs.python.org/issue45269 with self.assertRaisesRegex( diff --git a/Misc/NEWS.d/next/Library/2026-11-24-04-43-08.gh-issue-162525.Me7bYD.rst b/Misc/NEWS.d/next/Library/2026-11-24-04-43-08.gh-issue-162525.Me7bYD.rst new file mode 100644 index 00000000000000..4a8ebaddc4f947 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-24-04-43-08.gh-issue-162525.Me7bYD.rst @@ -0,0 +1,3 @@ +Fix the C :mod:`json` encoder writing the :meth:`~object.__str__` result of +:class:`str` subclasses used as *separators*, which produced invalid JSON. +It now writes their characters, like the pure Python encoder. diff --git a/Modules/_json.c b/Modules/_json.c index 250dd67d2a9687..e8fc029cf5fdfb 100644 --- a/Modules/_json.c +++ b/Modules/_json.c @@ -1469,8 +1469,11 @@ encoder_encode_string(PyEncoderObject *s, PyObject *obj) static int _steal_accumulate(PyUnicodeWriter *writer, PyObject *stolen) { - /* Append stolen and then decrement its reference count */ - int rval = PyUnicodeWriter_WriteStr(writer, stolen); + /* Append stolen and then decrement its reference count. + gh-148241: Avoid PyUnicodeWriter_WriteStr() which calls str(obj) + on str subclasses. */ + assert(PyUnicode_Check(stolen)); + int rval = _PyUnicodeWriter_WriteStr((_PyUnicodeWriter*)writer, stolen); Py_DECREF(stolen); return rval; } @@ -1626,7 +1629,8 @@ encoder_encode_key_value(PyEncoderObject *s, PyUnicodeWriter *writer, bool *firs } } else { - if (PyUnicodeWriter_WriteStr(writer, item_separator) < 0) { + if (_PyUnicodeWriter_WriteStr((_PyUnicodeWriter*)writer, + item_separator) < 0) { Py_DECREF(keystr); return -1; } @@ -1641,7 +1645,8 @@ encoder_encode_key_value(PyEncoderObject *s, PyUnicodeWriter *writer, bool *firs if (_steal_accumulate(writer, encoded) < 0) { return -1; } - if (PyUnicodeWriter_WriteStr(writer, s->key_separator) < 0) { + if (_PyUnicodeWriter_WriteStr((_PyUnicodeWriter*)writer, + s->key_separator) < 0) { return -1; } if (encoder_listencode_obj(s, writer, value, indent_level, indent_cache) < 0) { @@ -1820,7 +1825,7 @@ encoder_listencode_list(PyEncoderObject *s, PyUnicodeWriter *writer, // that mutates the sequence, invalidating this borrowed ref. Py_INCREF(obj); if (i) { - if (PyUnicodeWriter_WriteStr(writer, separator) < 0) { + if (_PyUnicodeWriter_WriteStr((_PyUnicodeWriter*)writer, separator) < 0) { Py_DECREF(obj); goto bail; }