TATECHATLAS
◎ English
Artificial intelligence / Guide

How sort_keys in json.dumps Gives Deterministic Key Order for Comparing Model JSON Responses

sort_keys=True makes json.dumps emit dictionary keys in sorted order, so two JSON responses with the same data but different key order serialize to identical strings. Sorting happens on the original Python keys before they are converted to JSON strings, so numeric keys sort by value.

On this page

Pass sort_keys=True to json.dumps (or json.dump). The encoder then sorts each dictionary's keys before writing the JSON object, producing one canonical byte-for-byte representation per data value. Because the sort runs on the original Python key objects before they are converted to strings, integer keys such as 2 and 10 are ordered numerically (2 before 10) rather than lexicographically. This makes serialized output stable across runs and safe for equality comparisons in regression tests, golden files, and model response diffing, provided both sides are serialized with the same settings.

Why deterministic key order matters when comparing JSON responses

JSON objects are, by specification, unordered mappings from string keys to values. Two JSON documents that differ only in the order their object members were written carry exactly the same data. Python's json module preserves the insertion order of the underlying dict by default, and the documentation notes that order is only lost if the underlying containers are unordered. That fidelity is useful for display, but it is a liability for testing: the same logical response can serialize differently depending on how a dict was built, how a model formatted its output, or how an upstream service ordered its fields.

Deterministic serialization removes that noise. When you compare json.dumps(expected, sort_keys=True) with json.dumps(actual, sort_keys=True), a difference in the resulting strings means a real difference in keys or values, not a meaningless difference in member order. The Python documentation explicitly frames sort_keys this way: it is useful for regression tests so that JSON serializations can be compared on a day-to-day basis. Reproducible comparisons also make golden-file diffs, checksums, and cache keys reliable.

import json

# Same data, different insertion order: default dumps can differ,
# sort_keys=True makes the serialization deterministic.
a = {"c": 0, "b": 0, "a": 0}
b = {"a": 0, "b": 0, "c": 0}

print(json.dumps(a) == json.dumps(b))                      # False
print(json.dumps(a, sort_keys=True) == json.dumps(b, sort_keys=True))  # True

Canonicalize both sides the same way: dump expected and actual responses with identical json.dumps arguments (sort_keys=True plus the same indent and separators), then compare strings or hashes. If one side is a raw JSON string from an external system, parse it with json.loads first so both sides go through the same encoder.

How sort_keys works inside json.dumps

json.dumps(obj, sort_keys=True) serializes obj to a JSON-formatted str, and when sort_keys is true the output of dictionaries is sorted by key. The default is False, which keeps each dict's own iteration order. The parameter applies recursively: every nested object encountered during encoding is emitted with its keys sorted, so the entire document gets one consistent order. The same flag exists on json.dump for writing to a file-like object and on the JSONEncoder class, and the command-line tool exposes it as --sort-keys (available since Python 3.5).

The crucial mechanical detail from the documentation: sort_keys sorts the keys before they are converted to strings. Sorting therefore uses the natural ordering of the Python key objects themselves. String keys are sorted lexicographically by their Unicode values; integer and float keys are sorted numerically. Only after ordering does the encoder apply the JSON key rule and stringify each key. Because sorting compares the original key objects, a single dict that mixes key types such as int and str raises TypeError with sort_keys=True, since those objects are not mutually comparable; keep each dict's keys homogeneous. This ordering choice is what makes the flag well-defined for dicts with non-string keys of one type, which JSON cannot represent directly.

import json

# Keys are sorted as Python objects before being converted to strings,
# so integer keys 2 and 10 are ordered numerically (2 before 10).
print(json.dumps({2: 'two', 10: 'ten'}, sort_keys=True))
# {"2": "two", "10": "ten"}

# String keys are sorted lexicographically by their Unicode values.
print(json.dumps({'b': 2, 'a': 1, 'c': 3}, sort_keys=True))
# {"a": 1, "b": 2, "c": 3}

# Mixing int and str keys in one dict with sort_keys=True raises TypeError,
# because the original key objects are not mutually comparable:
try:
    json.dumps({2: 'two', 'a': 1}, sort_keys=True)
except TypeError as e:
    print('TypeError:', e)
# TypeError: '<' not supported between instances of 'str' and 'int'

Key stringification and its consequences

JSON requires every object key to be a string; the JSON Schema specification states that in JSON the keys must always be strings, and shows that non-string keys such as {0.01: ...} are invalid JSON. Python dicts are more permissive: any hashable value can be a key. So during serialization the json module converts every dictionary key to a string using its conversion table: int and float keys become their decimal text, bool keys become true/false, None becomes null, and str keys pass through.

The docs warn about a direct consequence: because all keys are converted to strings, round-tripping a dict through dumps and loads may not return an equal dict. loads(dumps(x)) != x when x has non-string keys, since json.loads has no way to know that the key '2' was originally the integer 2. This is a structural fact of the format, not a bug, and it is exactly why sorting must happen before stringification: sorting the string forms would impose an arbitrary lexicographic order on what were originally numbers.

import json

x = {2: 'x'}
print(json.dumps(x))            # {"2": "x"}
print(json.loads(json.dumps(x)))  # {'2': 'x'}  -- key is now a string
print(json.loads(json.dumps(x)) == x)  # False: loads(dumps(x)) != x for non-string keys

Practical consequences for comparing model JSON responses

When you test an LLM or any service that returns JSON, the assertion you usually care about is semantic equality: same keys, same values, same structure. With sort_keys=True you can compare canonical strings directly, or compare hashes of those strings, and get a stable verdict regardless of the order in which either side emitted its object members. This also makes diffs readable: a unified diff of two sorted serializations shows real added, removed, or changed fields rather than a wall of reordered lines.

Pair the flag with fixed formatting for fully deterministic output: the same separators, indent, and ensure_ascii setting on both sides. Without fixed separators and spacing, two different writers can still produce different whitespace. The module's default separators are (', ', ': ') when indent is None and (',', ': ') otherwise, so choose and pin them explicitly if you compare output from different encoders.

import json

def canonical(obj):
    return json.dumps(obj, sort_keys=True, separators=(',', ':'), ensure_ascii=True)

response_a = {"model": "gpt", "usage": {"total": 3, "prompt": 1, "completion": 2}}
response_b = {"usage": {"completion": 2, "total": 3, "prompt": 1}, "model": "gpt"}

print(canonical(response_a) == canonical(response_b))  # True
print(canonical(response_a))
# {"model":"gpt","usage":{"completion":2,"prompt":1,"total":3}}

Trade-offs and limitations of sort_keys

Sorting costs extra work per object: every dictionary's keys must be ordered during encoding, which grows with the number of keys and nesting depth. For small test payloads this is negligible; for very large documents serialized in a hot path, measure before adopting it everywhere. The benefit is not free ordering, it is a canonical form, so apply it where determinism matters (tests, golden files, hashing, cache keys) and skip it where raw throughput matters and order is irrelevant.

There are correctness limits too. Sorting requires comparable keys within each dictionary: a dict that mixes int and str keys serializes fine without the flag (the encoder stringifies keys), but with sort_keys=True it raises TypeError because the original key objects are not mutually comparable. Keep each dict's keys homogeneous, or canonicalize heterogeneous payloads one dict at a time. Custom objects used as keys are not meaningfully sortable unless they define ordering, and keys of types outside str, int, float, bool, None are skipped or rejected depending on skipkeys. Determinism is guaranteed only for the data actually encodable by the encoder.

# No code needed here; see the worked example below.

Worked example: comparing two model responses

Suppose a model returns a payload as two dicts that contain the same data but were constructed in different orders, including numeric keys. Serialize both with sort_keys=True and compare the canonical strings. The numeric keys 2 and 10 are sorted by value, so '2' appears before '10' even though the string '10' would sort before '2' lexicographically, while the string keys sort lexicographically. Both serializations are identical, so the equality check returns True. Note that sort_keys works here because each dict's keys are compared among themselves: the encoder never has to order an int key against a str key. If you remove sort_keys, the two dicts serialize in their insertion orders and the string comparison can fail even though the data is the same.

Run this on Python 3.6 or later (any maintained 3.x works; all keyword arguments shown have been keyword-only since 3.6). The printed line is the observed output of the comparison, while the dumps lines illustrate the canonical form.

import json

# Two model responses with identical data but different construction order.
json_data_1 = {2: 'two', 10: 'ten', 'b': 2, 'a': 1, 'c': 3}
json_data_2 = {'c': 3, 'a': 1, 'b': 2, 10: 'ten', 2: 'two'}

# sort_keys=True requires comparable keys, so canonicalize each dict
# separately: numeric keys sort by value, string keys lexicographically.
s1 = json.dumps(json_data_1, sort_keys=True)
s2 = json.dumps(json_data_2, sort_keys=True)

print(s1)
print(s1 == s2)

# Expected output:
# {"2": "two", "10": "ten", "a": 1, "b": 2, "c": 3}
# True

# Without sort_keys the two dicts serialize in their own insertion
# orders and the string comparison can fail despite equal data:
print(json.dumps(json_data_1) == json.dumps(json_data_2))  # False

Alternatives and their limits

You can normalize at decode time instead of encode time. object_pairs_hook receives each decoded object as a list of key-value pairs, so you can return an ordered or sorted structure; it also lets you detect duplicate names, which the default decoder silently resolves to the last value. object_hook receives the decoded dict and can transform it, for example converting string keys back to ints. These hooks solve specific decoding needs but do not, by themselves, give you a canonical string for comparison unless you then re-serialize with sort_keys.

A custom JSONEncoder subclass can override default() to make custom objects serializable, and iterencode lets you stream output, but key ordering itself is controlled by the sort_keys flag rather than by default(). The simplest, most auditable approach for response comparison remains: parse both sides with json.loads, then compare json.dumps(parsed, sort_keys=True, <fixed formatting>) or compare the parsed structures directly with ==, which is order-insensitive for dicts anyway. String comparison of canonical forms is preferable when you also want stable hashes, diffs, or stored golden files.

import json

# Decode-time normalization alternative for external JSON text.
raw = '{"b": 2, "a": 1, "c": 3}'  # replace with a real external payload

parsed = json.loads(raw)                          # dict comparison is order-insensitive
canonical = json.dumps(parsed, sort_keys=True)    # canonical string for hashing/diffing

print(parsed == {"a": 1, "b": 2, "c": 3})  # True
print(canonical)                           # {"a": 1, "b": 2, "c": 3}

Choosing and scoping sort_keys in real scenarios

Use sort_keys=True when the comparison or artifact must be reproducible: regression tests against model outputs, golden-file snapshots, checksum-based cache keys, and cross-system diffing where you control serialization on at least one side. Normalize both sides through the same encoder settings so whitespace and escaping cannot masquerade as data differences. Keep in mind that canonical JSON is for comparison; it does not need to match what the model or service originally sent.

Be cautious in a few cases. Very large documents pay a sorting cost, so serialize canonically once and compare hashes rather than re-encoding repeatedly. Data round-tripped through JSON with numeric or boolean keys will come back with string keys, so do not assert dict equality against the original Python object. If another system produces the JSON, parse it with json.loads before canonicalizing; do not string-compare raw external text against your own dumps. And if model responses are only semantically similar rather than structurally identical (free-form text fields, variable wording), canonical JSON equality is the wrong tool; use a task-appropriate similarity or validation step instead.

import json

# End-to-end pattern for test assertions.
def assert_json_equal(expected, actual):
    assert (json.dumps(expected, sort_keys=True) ==
            json.dumps(actual, sort_keys=True)), 'JSON payloads differ'

assert_json_equal({"x": 1, "y": [2, 3]}, {"y": [2, 3], "x": 1})  # passes
print("payloads equal")

Things to check

  • Run the worked example on Python 3.6+ and confirm it prints True for the equality comparison.
  • Confirm that with sort_keys=True the int-keyed dict {2: 'two', 10: 'ten'} serializes in the order 2 then 10, demonstrating sorting by value before stringification, and that a separate str-keyed dict sorts lexicographically.
  • Remove sort_keys and confirm the two dicts can serialize with different member order, illustrating the problem the flag solves.
  • Call json.dumps({2: 'two', 'a': 1}, sort_keys=True) and confirm it raises TypeError ('<' not supported between instances of 'str' and 'int'), since sort_keys compares the original key objects.

sort_keys guarantees deterministic ordering only for the key types json.dumps can encode and compare: it sorts before string conversion, so numeric keys sort by value, but keys that lack a natural ordering or that come from custom classes without ordering support are not reliably sortable, and round-tripped non-string keys come back as strings. Performance overhead grows with document size and nesting, so apply canonical serialization where reproducibility matters rather than blindly everywhere.

Sources

  1. Python: json ↗
  2. JSON Schema: objects and required properties ↗
Back to top ↑