From 72f3c4e3ff5febcf1ac4bb03b0bb7d96fb626525 Mon Sep 17 00:00:00 2001 From: Hood Chatham Date: Wed, 9 Jul 2025 17:00:12 +0200 Subject: [PATCH 6/9] Teach json encoder.py to encode jsnull --- Lib/json/encoder.py | 9 +++++++++ Modules/_json.c | 8 +++++--- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/Lib/json/encoder.py b/Lib/json/encoder.py index 5cf6d64f3ea..a75ea21baff 100644 --- a/Lib/json/encoder.py +++ b/Lib/json/encoder.py @@ -33,6 +33,7 @@ del i INFINITY = float('inf') +_JSNULL = None def py_encode_basestring(s): """Return a JSON representation of a Python string @@ -303,6 +304,8 @@ def _iterencode_list(lst, _current_indent_level): yield buf + _encoder(value) elif value is None: yield buf + 'null' + elif value is _JSNULL: + yield buf + 'null' elif value is True: yield buf + 'true' elif value is False: @@ -372,6 +375,8 @@ def _iterencode_dict(dct, _current_indent_level): key = 'false' elif key is None: key = 'null' + elif key is _JSNULL: + key = 'null' elif isinstance(key, int): # see comment for int/float in _make_iterencode key = _intstr(key) @@ -393,6 +398,8 @@ def _iterencode_dict(dct, _current_indent_level): yield _encoder(value) elif value is None: yield 'null' + elif value is _JSNULL: + yield 'null' elif value is True: yield 'true' elif value is False: @@ -428,6 +435,8 @@ def _iterencode(o, _current_indent_level): yield _encoder(o) elif o is None: yield 'null' + elif o is _JSNULL: + yield 'null' elif o is True: yield 'true' elif o is False: diff --git a/Modules/_json.c b/Modules/_json.c index 2f82a69a157..83d1c3e2f62 100644 --- a/Modules/_json.c +++ b/Modules/_json.c @@ -1398,11 +1398,13 @@ encoder_call(PyObject *op, PyObject *args, PyObject *kwds) return result; } +extern PyObject* py_jsnull; + static PyObject * _encoded_const(PyObject *obj) { /* Return the JSON string representation of None, True, False */ - if (obj == Py_None) { + if (obj == Py_None || obj == py_jsnull) { return &_Py_ID(null); } else if (obj == Py_True) { @@ -1482,7 +1484,7 @@ encoder_listencode_obj(PyEncoderObject *s, PyUnicodeWriter *writer, PyObject *newobj; int rv; - if (obj == Py_None) { + if (obj == Py_None || obj == py_jsnull) { return PyUnicodeWriter_WriteASCII(writer, "null", 4); } else if (obj == Py_True) { @@ -1592,7 +1594,7 @@ encoder_encode_key_value(PyEncoderObject *s, PyUnicodeWriter *writer, bool *firs else if (PyFloat_Check(key)) { keystr = encoder_encode_float(s, key); } - else if (key == Py_True || key == Py_False || key == Py_None) { + else if (key == Py_True || key == Py_False || key == Py_None || key == py_jsnull) { /* This must come before the PyLong_Check because True and False are also 1 and 0.*/ keystr = _encoded_const(key); -- 2.43.0