Skip to content

Commit cf25af8

Browse files
authored
Merge pull request #14 from vertexproject/dict_keys
Dictionary keys must be strings
2 parents 7eb65e0 + 00b5cd4 commit cf25af8

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

tests/test_document.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,27 @@ def test_document_none_type():
190190
assert doc.as_obj == [None]
191191

192192

193+
def test_document_dict_type():
194+
"""
195+
Ensure we can load and dump the dict type.
196+
"""
197+
doc = Document('{"a": "b"}')
198+
assert doc.dumps() == '{"a":"b"}'
199+
assert doc.as_obj == {'a': 'b'}
200+
201+
doc = Document({"a": "b"})
202+
assert doc.dumps() == '{"a":"b"}'
203+
assert doc.as_obj == {'a': 'b'}
204+
205+
with pytest.raises(TypeError) as exc:
206+
doc = Document({1: 'b'})
207+
assert exc.value.args[0] == 'Dictionary keys must be strings'
208+
209+
with pytest.raises(TypeError) as exc:
210+
doc = Document({'\ud83d\ude47': 'foo'})
211+
assert exc.value.args[0] == 'Dictionary keys must be strings'
212+
213+
193214
def test_document_get_pointer():
194215
"""
195216
Ensure JSON pointers work.

yyjson/document.c

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -379,6 +379,13 @@ static inline yyjson_mut_val *mut_primitive_to_element(
379379
while (PyDict_Next(obj, &i, &key, &value)) {
380380
Py_ssize_t str_len;
381381
const char *str = PyUnicode_AsUTF8AndSize(key, &str_len);
382+
if (yyjson_unlikely(str == NULL)) {
383+
PyErr_Format(PyExc_TypeError,
384+
"Dictionary keys must be strings",
385+
Py_TYPE(obj)->tp_name
386+
);
387+
return NULL;
388+
}
382389
object_value = mut_primitive_to_element(self, doc, value);
383390
if (yyjson_unlikely(object_value == NULL)) {
384391
return NULL;

0 commit comments

Comments
 (0)