From 00b5cd465d95120d086bc422c9e70047595bd12d Mon Sep 17 00:00:00 2001 From: blackout Date: Mon, 21 Apr 2025 17:01:23 -0400 Subject: [PATCH] Dict keys must be strings --- tests/test_document.py | 21 +++++++++++++++++++++ yyjson/document.c | 7 +++++++ 2 files changed, 28 insertions(+) diff --git a/tests/test_document.py b/tests/test_document.py index 62afd04..bf82177 100644 --- a/tests/test_document.py +++ b/tests/test_document.py @@ -166,6 +166,27 @@ def test_document_none_type(): assert doc.as_obj == [None] +def test_document_dict_type(): + """ + Ensure we can load and dump the dict type. + """ + doc = Document('{"a": "b"}') + assert doc.dumps() == '{"a":"b"}' + assert doc.as_obj == {'a': 'b'} + + doc = Document({"a": "b"}) + assert doc.dumps() == '{"a":"b"}' + assert doc.as_obj == {'a': 'b'} + + with pytest.raises(TypeError) as exc: + doc = Document({1: 'b'}) + assert exc.value.args[0] == 'Dictionary keys must be strings' + + with pytest.raises(TypeError) as exc: + doc = Document({'\ud83d\ude47': 'foo'}) + assert exc.value.args[0] == 'Dictionary keys must be strings' + + def test_document_get_pointer(): """ Ensure JSON pointers work. diff --git a/yyjson/document.c b/yyjson/document.c index 69c6c5f..d913984 100644 --- a/yyjson/document.c +++ b/yyjson/document.c @@ -364,6 +364,13 @@ static inline yyjson_mut_val *mut_primitive_to_element( while (PyDict_Next(obj, &i, &key, &value)) { Py_ssize_t str_len; const char *str = PyUnicode_AsUTF8AndSize(key, &str_len); + if (yyjson_unlikely(str == NULL)) { + PyErr_Format(PyExc_TypeError, + "Dictionary keys must be strings", + Py_TYPE(obj)->tp_name + ); + return NULL; + } object_value = mut_primitive_to_element(self, doc, value); if (yyjson_unlikely(object_value == NULL)) { return NULL;