SQLSTATE 22P02 ERROR Class 22: Data Exception

invalid_text_representation invalid input syntax for type json — 22P02

PostgreSQL error "invalid input syntax for type json" (SQLSTATE 22P02): what it means, common causes, and how to fix it.

PG 12, 13, 14, 15, 16, 17, 18 Official docs
Last reviewed May 2025 Grounded in source

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 json and jsonb require 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

  1. Serialize JSON with a real library rather than string concatenation.
  2. Validate the payload before insert; ensure double quotes and no trailing commas.
  3. Use parameter binding so quoting is handled correctly.

Related & next steps

Reference: PostgreSQL 18 Section 8.14 “JSON Types”.

Was this helpful?