Visitar URL original
gh-100272: Fix JSON serialization of OrderedDict by serhiy-storchaka · Pull Request #100273 · python/cpython · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
gh-100272: Fix JSON serialization of OrderedDict
It now preserves the order of keys.
  • Loading branch information
serhiy-storchaka committed Dec 15, 2022
commit 3262ea64b84bf19e00c5e3fdf9d56b1d28e6326b
11 changes: 11 additions & 0 deletions Lib/test/test_json/test_default.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import collections
from test.test_json import PyTest, CTest


Expand All @@ -7,6 +8,16 @@ def test_default(self):
self.dumps(type, default=repr),
self.dumps(repr(type)))

def test_ordereddict(self):
od = collections.OrderedDict(a=1, b=2)

@rhettinger rhettinger Dec 15, 2022 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suggest adding a few more pairs to this to make this a more convincing test.

od.move_to_end('a')
self.assertEqual(
self.dumps(od),
'{"b": 2, "a": 1}')
self.assertEqual(
self.dumps(od, sort_keys=True),
'{"a": 1, "b": 2}')


class TestPyDefault(TestDefault, PyTest): pass
class TestCDefault(TestDefault, CTest): pass
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix JSON serialization of OrderedDict. It now preserves the order of keys.
7 changes: 3 additions & 4 deletions Modules/_json.c
Original file line number Diff line number Diff line change
Expand Up @@ -1570,10 +1570,9 @@ encoder_listencode_dict(PyEncoderObject *s, _PyUnicodeWriter *writer,
*/
}

if (s->sort_keys) {

items = PyDict_Items(dct);
if (items == NULL || PyList_Sort(items) < 0)
if (s->sort_keys || !PyDict_CheckExact(dct)) {
items = PyMapping_Items(dct);
if (items == NULL || (s->sort_keys && PyList_Sort(items) < 0))
goto bail;

for (Py_ssize_t i = 0; i < PyList_GET_SIZE(items); i++) {
Expand Down