Skip to contentSaltar al contenido
125+ QA and SEO checks per page

JSON Parser Implementation in Python

14 min readintermediate
Website QA and SEO audits

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

A JSON parser turns a byte stream into values, and writing one is the standard exercise in tokenising and recursive descent because the grammar fits on a postcard. In production, though, nobody writes one: all eight of these languages either ship a parser or have one universal library, so the question that actually matters is what the parser you already have does with the awkward parts of the format. Those parts are the same everywhere and are the source of nearly every real bug: the specification puts no limit on the precision of a number while most parsers decode into a 64-bit float, it says nothing about what a duplicate key means, and it says nothing about how a parser should defend itself against a hostile document. Each language answered those three questions differently, and the differences are exactly where data gets silently corrupted.

JSON Parser in Python: what you actually reach for

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.

Python implementation

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.
python
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 Free

The Python-specific trap

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.

Performance in Python, beyond the O(n)

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. The asymptotic cost is the same in every language, O(n) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port JSON Parser between languages.

Real-World Applications

JSON Parser applies wherever its problem shape appears in your own code. In Python, check whether the standard library or a well maintained package already provides it before you write your own. Understanding JSON Parser helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

JSON Parser appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose JSON Parser over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of JSON Parser to build pattern recognition. In Python, demonstrate proficiency with list comprehensions and generator expressions to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Python code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Studying for this? GitHub Copilot free tiers and academic plans are laid out on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.