Skip to content

Commit 05e06d0

Browse files
committed
Skip overridden items for empty dictionaries in JSON encoding
Split the Python 3.14-compatible empty native dictionary fast path from #8954. Extend the existing JSON snippet with root, nested, sorting, and nonempty subclass regression coverage. Assisted-by: OpenAI Codex:model identifier unavailable
1 parent d0dfcb5 commit 05e06d0

2 files changed

Lines changed: 22 additions & 0 deletions

File tree

‎crates/stdlib/src/json.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1160,6 +1160,10 @@ mod _json {
11601160
out: &mut Wtf8Buf,
11611161
vm: &VirtualMachine,
11621162
) -> PyResult<()> {
1163+
if dict.is_empty() {
1164+
out.push_str("{}");
1165+
return Ok(());
1166+
}
11631167
let mut items = self.dict_items(obj, dict, vm)?;
11641168
if items.is_empty() {
11651169
out.push_str("{}");

‎extra_tests/snippets/stdlib_json.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,24 @@ def json_load(obj):
6767
assert "{}" == json_dump({})
6868
assert round_trip_test({"a": "b"})
6969

70+
71+
class EmptyDictWithItems(dict):
72+
def items(self):
73+
raise AssertionError("items() must not be called for an empty dictionary")
74+
75+
76+
for sort_keys in (False, True):
77+
assert json.dumps(EmptyDictWithItems(), sort_keys=sort_keys) == "{}"
78+
assert json.dumps([EmptyDictWithItems()], sort_keys=sort_keys) == "[{}]"
79+
80+
81+
class NonemptyDictWithItems(dict):
82+
def items(self):
83+
return [("replacement", 2)]
84+
85+
86+
assert json.dumps(NonemptyDictWithItems(original=1)) == '{"replacement": 2}'
87+
7088
# should reject non-str keys in jsons
7189
assert_raises(json.JSONDecodeError, lambda: json.loads('{3: "abc"}'))
7290
assert_raises(json.JSONDecodeError, lambda: json_load('{3: "abc"}'))

0 commit comments

Comments
 (0)