Why json.dumps converts non-string dictionary keys to strings and how it breaks token ID mapping
JSON only allows string keys for objects. Consequently, json.dumps converts numeric Python dictionary keys to strings, meaning loads(dumps(x)) != x for dictionaries with non-string keys. This causes KeyErrors when looking up integer token IDs in dictionaries loaded from JSON.
On this page
The short answer
In JSON, object keys must always be strings, whereas Python dictionaries allow any hashable keys. During serialization via json.dumps, all keys are converted to strings; Python's documentation warns that loads(dumps(x)) != x if x has non-string keys. For a dictionary {50256: '<|endoftext|>', 50257: '<|unk|>'}, a round-trip results in {'50256': '<|endoftext|>', '50257': '<|unk|>'}. While the data remains, searching for vocab[token_id] using an integer token_id triggers a KeyError. Solutions include: explicitly converting keys after loads (e.g., int(k)), using object_hook or object_pairs_hook for automatic type restoration, or storing the dictionary as a list of pairs [[50256, '<|endoftext|>'], [50257, '<|unk|>']] and reconstructing the dict manually. Data contracts should assume string keys because JSON Schema considers objects with non-string keys invalid.
Why JSON Requires String Keys
JSON is defined as a data interchange format inspired by JavaScript object literal syntax. In JSON, an object is a mapping of keys to values, and by specification, keys must always be strings. A Python dictionary, by contrast, allows any hashable object as a key: integers, tuples, booleans, or None.
This is a fundamental limitation of the format, not a specific implementation detail. Data such as {0.01: ' cm ', 1: ' m ', 1000: ' km '} with non-string keys is simply invalid JSON. Any serializer aiming to produce valid JSON must coerce keys to strings, which json.dumps does automatically and silently.
Practical tip
If a dictionary with numeric keys is serialized frequently, implement a single helper using object_pairs_hook that recognizes numeric keys via regular expressions and converts them to integers. Use this helper across the entire pipeline to eliminate type mismatch between modules reading the same JSON file.
What json.dumps Does to Non-String Keys
The json module in Python's standard library converts Python objects to JSON based on a conversion table. A dictionary becomes a JSON object, and all dictionary keys are converted to strings. Python's documentation explicitly warns that if a dictionary is converted to JSON and back, the resulting dictionary may not equal the original: loads(dumps(x)) != x if x has non-string keys.
This is not an error or an exception; serialization succeeds, but the key type is lost. If a key is not a str, int, float, bool, or None, json.dumps raises a TypeError by default (unless skipkeys=True). However, numeric keys are basic types and are serialized without error, simply losing their original type.
Demonstration with Numeric Keys
Consider a dictionary mapping integer token IDs to their string representations. After serialization and reloading, the keys become strings. Comparing the original and the round-tripped dictionary returns False because the string '50256' is not equal to the integer 50256 in Python.
import json
vocab = {50256: '<|endoftext|>', 50257: '<|unk|>'}
json_string = json.dumps(vocab)
loaded_vocab = json.loads(json_string)
print(f"Original: {vocab}")
print(f"Loaded: {loaded_vocab}")
print(f"Equal? {vocab == loaded_vocab}")
# Output:
# Original: {50256: '<|endoftext|>', 50257: '<|unk|>'}
# Loaded: {'50256': '<|endoftext|>', '50257': '<|unk|>'}
# Equal? FalseBehavior of sort_keys with Numeric Keys
Python's documentation notes a nuance: sort_keys sorts keys before they are converted to strings. Therefore, numeric keys are ordered by their numeric value, not their string representation. For example, with sort_keys=True, a dictionary {10: 'a', 2: 'b'} is serialized in the order 2, 10, rather than lexicographically ('10' comes before '2' as a string).
import json
data = {10: 'a', 2: 'b'}
# Sorted by numeric value (2 < 10)
print(json.dumps(data, sort_keys=True))
# Output: {"2": "b", "10": "a"}Where This Breaks Token ID Mapping
A typical scenario in LLM pipelines: a vocabulary dictionary mapping token_id (int) to token (str) is serialized to JSON. After loading, keys become strings. Searching for vocab[token_id] with an integer ID triggers a KeyError, even though the data is present.
This error is insidious because it doesn't appear during loading, but later during model output decoding where token_ids are provided as integers. A KeyError: 50256 looks confusing because the key '50256' is visually present when printing the dictionary.
import json
# Simulated loaded vocab from JSON
vocab = {'50256': '<|endoftext|>', '50257': '<|unk|>'}
token_id = 50256
try:
print(vocab[token_id])
except KeyError as e:
print(f"KeyError: {e} - The key is a string '50256', but we searched for int 50256")
# Output: KeyError: 50256 - The key is a string '50256', but we searched for int 50256Schema Validation and Invalid Numeric Keys
JSON Schema defines an object as a mapping of string keys to values. Examples of data with numeric keys, such as {0.01: ' cm ', 1: ' m ', 1000: ' km '}, are marked as non-compliant. This means data contracts described by JSON Schema inherently assume string keys.
If a pipeline validates data against JSON Schema, a dictionary with numeric keys will be valid after serialization (since keys are already strings), but the original Python object does not match the JSON object semantics. This reinforces the need to explicitly fix key types at the serialization boundary.
Strategies for Restoring Key Types
The most direct method is explicit conversion after loads: {int(k): v for k, v in raw.items()}. This works only if all keys are known to be numeric.
A more automated approach uses object_hook or object_pairs_hook during loads. These hooks are called for every decoded JSON object and can replace the resulting dict with a structure containing restored types. object_pairs_hook receives an ordered list of pairs, which is useful for custom decoders.
Alternatively, store the dictionary as a list of pairs [[50256, '<|endoftext|>'], [50257, '<|unk|>']] and reconstruct the dict manually. This preserves types without hooks but increases data size and requires manual reconstruction code.
import json
json_data = '{"50256": "<|endoftext|>", "50257": "<|unk|>"}'
# Method 1: Dictionary comprehension
raw = json.loads(json_data)
vocab_fixed = {int(k): v for k, v in raw.items()}
# Method 2: object_pairs_hook
def restore_ints(pairs):
return {int(k): v for k, v in pairs}
vocab_hook = json.loads(json_data, object_pairs_hook=restore_ints)
print(f"Fixed: {vocab_fixed}")
print(f"Hooked: {vocab_hook}")
# Output:
# Fixed: {50256: '<|endoftext|>', 50257: '<|unk|>'}
# Hooked: {50256: '<|endoftext|>', 50257: '<|unk|>'} Practical Checklist for Token Pipelines
Do not rely on JSON round-trips for dictionaries with numeric keys: Python documentation warns that loads(dumps(x)) != x in this case. Fix key types in the data contract and test equality after serialization in CI.
If keys are known to be numeric, convert them explicitly after loads or use object_pairs_hook. If key types are mixed, store pairs in an array and restore the dictionary manually. Note that third-party libraries like orjson may handle keys differently than the standard json module.
Things to check
- After json.loads, verify the type of at least one key: isinstance(key, str) should be True for a dictionary loaded from JSON that originally had numeric keys.
- Compare loads(dumps(vocab)) == vocab in a test; for a dictionary with integer keys, this must return False.
- Ensure that vocab[token_id] lookup with an integer token_id either works (because keys were converted back) or is explicitly documented as requiring a string key.
Where this applies
The recommendation to use int(k) applies only when all keys are known to be numeric; mixed key types require an explicit contract. Storing pairs in an array increases data size and requires separate reconstruction code. Sources do not cover the behavior of third-party JSON libraries (e.g., orjson), which may handle keys differently.