JSONDecodeError Reports Parse Position
Catch json.JSONDecodeError and read msg, pos, lineno, and colno to show exactly where a malformed payload stopped parsing.
Code
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
CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.HAR Waterfall AnalyzerInspect HTTP Archive (HAR 1.2) JSON files locally to summarize total requests, status codes, MIME types, slowest calls, and timing waterfalls.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.