Diagnostic Queries
Symptoms
A value being stored as json/jsonb is not well-formed JSON. PostgreSQL validates JSON on input and raises SQLSTATE 22P02 (invalid_text_representation) with a hint about where parsing failed.
- Often caused by single quotes, trailing commas, or unquoted keys.
- The message points near the parse failure (token/position).
- Both
jsonandjsonbrequire valid JSON syntax.
What the server log shows
ERROR: invalid input syntax for type json
DETAIL: Token "'" is invalid.
CONTEXT: JSON data, line 1: {'a'...
Why PostgreSQL raises this — what the manual says
Section 8.14.1 JSON Input and Output Syntax:
“The input/output syntax for the JSON data types is as specified in RFC 7159.”
JSON input is parsed against the JSON grammar. JSON requires double-quoted keys and strings, no trailing commas, and specific literals (true, false, null). Violations fail with 22P02 before storage.
Common causes
- Single quotes instead of double quotes for keys/strings.
- Trailing commas or unquoted object keys.
- Concatenating strings that produce malformed JSON.
- Double-encoded or truncated payloads.
How to fix it
- Serialize JSON with a real library rather than string concatenation.
- Validate the payload before insert; ensure double quotes and no trailing commas.
- Use parameter binding so quoting is handled correctly.
Related & next steps
Reference: PostgreSQL 18 Section 8.14 “JSON Types”.
Thanks — noted. This helps keep the database accurate.