JSON Parser Implementation in Python
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓JSON Parser runs in O(n) time and O(n) space, in Python as in every other language.
- ✓The json module, with loads and dumps, plus a JSONDecoder that accepts hooks: object_pairs_hook receives the key-value pairs as a list before they collapse into a dictionary, parse_float and parse_int override the numeric conversions, and parse_constant intercepts the non-standard literals.
- ✓Use object_pairs_hook when duplicate keys matter, since it is the only place you can see them, and parse_float=decimal.Decimal when the payload carries money and a float would round it.
- ✓The Python trap: json.loads accepts NaN, Infinity and -Infinity by default, and none of the three is valid JSON.
- ✓The module has a C accelerator that is used automatically, so json.loads is not interpreted.
What JSON Parser actually is
JSON Parser in Python: what you actually reach for
Python implementation
import json
from decimal import Decimal
def reject_constant(name: str):
# json.loads accepts NaN / Infinity / -Infinity by DEFAULT. None of
# them is valid JSON, and a strict consumer downstream will reject
# the document you just "validated".
raise ValueError(f"non-standard JSON constant: {name}")
def strict_loads(text: str):
return json.loads(text, parse_constant=reject_constant)
# Money: the default float conversion rounds. Decimal does not.
order = json.loads('{"total": 1.15}', parse_float=Decimal)
# {'total': Decimal('1.15')} -- not 1.1499999999999999
# Duplicate keys are silently collapsed, last one winning. The pairs hook
# is the ONLY place you can see that it happened.
def no_duplicates(pairs):
seen = {}
for key, value in pairs:
if key in seen:
raise ValueError(f"duplicate key: {key!r}")
seen[key] = value
return seen
json.loads('{"a": 1, "a": 2}') # {'a': 2}, no warning
# json.loads('{"a": 1, "a": 2}', object_pairs_hook=no_duplicates)
# -> ValueError: duplicate key: 'a'Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Python-specific trap
Performance in Python, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for JSON Parser?
The json module, with loads and dumps, plus a JSONDecoder that accepts hooks: object_pairs_hook receives the key-value pairs as a list before they collapse into a dictionary, parse_float and parse_int override the numeric conversions, and parse_constant intercepts the non-standard literals.
What is the most common Python mistake when implementing JSON Parser?
json.loads accepts NaN, Infinity and -Infinity by default, and none of the three is valid JSON. A document you have validated with the standard library can therefore contain a float that breaks arithmetic downstream and that a strict parser elsewhere in your system will reject, so the round trip fails at the far end rather than at the boundary where it was introduced. Passing parse_constant is what refuses them. Separately, since Python 3.11 an integer literal longer than four thousand three hundred digits raises ValueError, a limit added in response to CVE-2020-10735 because converting such an integer to a string is quadratic and was a denial-of-service vector.
How does JSON Parser actually perform in Python?
The module has a C accelerator that is used automatically, so json.loads is not interpreted. Third-party parsers such as orjson are faster still, but they deliberately differ on exactly the edge cases above, so swapping them in changes behaviour on NaN, on subclasses of dict, and on integer size. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? GitHub Copilot free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.