Skip to content

gh-59598: Ignore leading whitespace in JSONDecoder.raw_decode#153018

Closed
mayank-dev-15 wants to merge 1 commit into
python:mainfrom
mayank-dev-15:fix-json-raw-decode-whitespace
Closed

gh-59598: Ignore leading whitespace in JSONDecoder.raw_decode#153018
mayank-dev-15 wants to merge 1 commit into
python:mainfrom
mayank-dev-15:fix-json-raw-decode-whitespace

Conversation

@mayank-dev-15

@mayank-dev-15 mayank-dev-15 commented Jul 4, 2026

Copy link
Copy Markdown

Summary

Fixes #59598

JSONDecoder.raw_decode() raises JSONDecodeError on strings with leading whitespace (e.g., ' {"key": "value"}'), while JSONDecoder.decode() handles it fine. This is inconsistent behavior.

Changes

  • Modify raw_decode() to accept an optional _w parameter (defaulting to WHITESPACE.match) to skip leading whitespace before decoding
  • Simplify decode() to call raw_decode(s) instead of manually computing the whitespace end index
  • The fix correctly handles the idx parameter — whitespace is skipped at any offset, not just the start

Before

>>> decoder = json.JSONDecoder()
>>> decoder.raw_decode('  {}')
JSONDecodeError: Expecting value: line 1 column 1 (char 0)

After

>>> decoder = json.JSONDecoder()
>>> decoder.raw_decode('  {}')
({}, 3)

Tests

Added TestRawDecode test class with tests for leading whitespace in raw_decode, covering both Python and C implementations.

raw_decode now ignores leading whitespace before the JSON value,
matching the behavior of decode(). Previously, passing a string like
'  {}' to raw_decode would raise JSONDecodeError.

The fix uses the existing WHITESPACE regex to skip whitespace at
any offset, preserving correct behavior with the idx parameter.
@bedevere-app

bedevere-app Bot commented Jul 4, 2026

Copy link
Copy Markdown

Most changes to Python require a NEWS entry. Add one using the blurb_it web app or the blurb command-line tool.

If this change has little impact on Python users, wait for a maintainer to apply the skip news label instead.

@python-cla-bot

python-cla-bot Bot commented Jul 4, 2026

Copy link
Copy Markdown

The following commit authors need to sign the Contributor License Agreement:

CLA not signed

@picnixz

picnixz commented Jul 4, 2026

Copy link
Copy Markdown
Member

There is already an open PR. Please don't open PRs when there are already PRs, even if stale. It's polite to first ask the other PR's author if they are willing to continue their work.

@picnixz picnixz closed this Jul 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

JSONDecoder.raw_decode breaks on leading whitespace

2 participants