JSONDecodeError Reports Parse Position

Catch json.JSONDecodeError and read msg, pos, lineno, and colno to show exactly where a malformed payload stopped parsing.

PythonData Integrity

Code

pythonsnippet
19 lines
import json

# json.loads failures raise JSONDecodeError with locator fields:
# msg says what went wrong, pos is the character offset, and
# lineno/colno point into the payload line by line
payloads = [
    '{"region": "us",\n  "retries": many}',
    '{"region": "us"',
]

for payload in payloads:
    try:
        json.loads(payload)
        print('parsed  :', payload.splitlines()[0])
    except json.JSONDecodeError as error:
        print('message :', error.msg)
        print('position:', error.pos)
        print('line/col:', error.lineno, error.colno)
        print('at text :', repr(payload.splitlines()[error.lineno - 1][error.colno - 1:]))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

message : Expecting value
position: 29
line/col: 1 30
at text : 'many}'
message : Expecting ',' delimiter
position: 15
line/col: 1 16
at text : ''

What the code does

One loop does the cycling here: for payload in payloads. JSONDecodeError is not tied to any input check: it fires whenever execution reaches that line.

Demo state sits in top-level bindings: payloads.

What to watch for

  • Nothing to install: the snippet stays inside the standard library.

Using it

Output lines are prefixed (parsed :, message :, position:), making each step’s effect easy to spot.

Key statements

except json.JSONDecodeError as error:
    print('message :', error.msg)
    print('position:', error.pos)
    print('line/col:', error.lineno, error.colno)
    print('at text :', repr(payload.splitlines()[error.lineno - 1][error.colno - 1:]))

Interactive Tools for This Topic

FAQ

Is input validated before use?
There is no validation gate: the `JSONDecodeError` raise happens unconditionally whenever its line executes.
Does the runtime need any help from npm, pip, cargo, or the like?
No — the package manager has nothing to do here; nothing is declared. Every import resolves inside the standard library — `json`. Its state lives in module-level bindings: `payloads`.