Items in JSON object are out of order using json.dumps?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
In Python 3.6 and earlier, json.dumps() did not preserve dictionary insertion order because dict was unordered. Starting with Python 3.7, dict officially maintains insertion order, and json.dumps() outputs keys in insertion order by default. If you need alphabetical key ordering, use json.dumps(data, sort_keys=True). If you are seeing unexpected order, it is because the dictionary was constructed in a different order than you expected, or you are using Python 3.6 or earlier.
Default Behavior (Python 3.7+)
Since Python 3.7, dict preserves insertion order as a language guarantee (it was an implementation detail in CPython 3.6). json.dumps() respects this order.
Sorting Keys Alphabetically
sort_keys=True sorts all keys alphabetically at every nesting level. This is useful for deterministic output, diffing, and version control.
Why Order Might Seem Wrong
The JSON output order mirrors the dict insertion order. If the source data arrives in an unexpected order, the JSON reflects that.
OrderedDict (Pre-Python 3.7)
In Python 3.7+, regular dict provides the same ordering guarantee, making OrderedDict unnecessary for this purpose.
Parsing JSON with Preserved Order
Custom Key Order
Pretty Printing with Order
Deterministic JSON for Hashing or Comparison
separators=(',', ':') removes extra whitespace for minimal, deterministic output.
JSON Spec and Key Order
The JSON specification (RFC 8259) states:
An object is an unordered collection of zero or more name/value pairs.
This means:
- JSON parsers are not required to preserve key order
{"a":1,"b":2}and{"b":2,"a":1}are semantically equal- Applications should not depend on key order in JSON
Python's json module preserves order as a convenience, but other languages and tools may not.
Common Pitfalls
- Expecting alphabetical order by default:
json.dumps()uses insertion order, not alphabetical. Usesort_keys=Trueif you need alphabetical. - Comparing JSON strings directly:
'{"a":1,"b":2}' != '{"b":2,"a":1}'as strings, but they are equivalent JSON. Usejson.loads()and compare dictionaries, or usesort_keys=Truefor canonical form. - Assuming all parsers preserve order: JavaScript's
JSON.parse()preserves order in modern engines, but the spec does not guarantee it. Databases, APIs, and older parsers may reorder keys. - Nested ordering:
sort_keys=Truesorts keys at all levels. If you need sorting only at the top level, you must build the ordered dict manually and usesort_keys=False. - Performance of sort_keys: Sorting adds O(k log k) overhead per object (k = number of keys). For very large JSON with thousands of keys per object, this can be measurable.
Summary
- Python 3.7+
dictpreserves insertion order, andjson.dumps()respects it - Use
sort_keys=Truefor alphabetical ordering at all nesting levels - Use
separators=(',', ':')withsort_keys=Truefor deterministic canonical JSON - The JSON spec says objects are unordered, so do not depend on key order across systems
- For custom key order, build an ordered dict with a comprehension before serializing
- Compare JSON by parsing to dicts, not by comparing strings
Related reading
- Iterate a list with indexes
- Iterate an iterator by chunks of n in Python?
- Iterate over model instance field names and values in template
- Iterate over object attributes in python
- Iterating each character in a string using Python
- Iterating over dictionaries using 'for' loops
- Iterating over every two elements in a list
- Iterating over tf.Tensor is not allowed AutoGraph is disabled in this function
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.