Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Serialize JSON with sorted keys

Convert Python objects to JSON strings with object keys sorted for deterministic output.

Python practice15 minModules & Standard LibraryIntermediateLast updated March 23, 2026

Problem statement

Write a function json_sorted(obj) that serializes a Python object to a JSON string where the keys of all JSON objects are sorted. Use standard JSON encoding semantics (e.g., None -> null, True/False -> true/false). The output should be deterministic so the same input always produces the same string representation.

Task

Implement json_sorted(obj) that returns a JSON string with object keys sorted lexicographically (applies recursively to nested objects).

Examples

Sort top-level keys

Input

json_sorted({'b': 2, 'a': 1})

Output

{"a": 1, "b": 2}

Top-level object keys are sorted alphabetically in the resulting JSON string.

Input format

A Python object composed of dicts, lists, strings, numbers, booleans, and None passed to json_sorted(obj)

Output format

A JSON-formatted string with object keys sorted

Constraints

- Use only the Python standard library. - Maintain JSON semantics. - The serialized string must be deterministic for the same input. - Keep default spacing produced by json.dumps for readability.

Samples

Sample 1

Input

json_sorted({'b':1, 'a':2})

Output

{"a": 2, "b": 1}

Keys 'a' and 'b' are ordered in the output string.