Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

PostgreSQL Error 22032: Invalid JSON Text Fix

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Error 22032 (invalid_json_text) means PostgreSQL tried to cast a string to json or jsonb and the string was not valid JSON. The fix is to find the offending row, correct or reject the bad text, and only then change the column type or run the insert. You cannot silence this error with a setting; the input itself has to be valid JSON.

The error is raised by the JSON input functions, so it appears in three common situations: inserting or updating a json/jsonb column with malformed text, running a cast such as '...'::jsonb, or converting an existing text column with ALTER TABLE ... USING col::jsonb. The message usually includes a detail line like "Token \"x\" is invalid" or "Expected end of input", which points at the first bad character. Because PostgreSQL validates the whole document, one stray comma or single quote fails the entire statement.

What You'll Need

  • Access to the database with a role that can read the affected table and, for fixes, update it.
  • A SQL client (psql, pgAdmin, DBeaver or similar) so you can run diagnostic queries.
  • The exact statement and parameter values that produced the error, or the name of the table and column being converted.
  • Backups or a transaction you can roll back before changing column types or deleting rows.

Step-by-Step

  1. Read the full error, not just the code. PostgreSQL returns a message, a detail and sometimes a hint. The detail names the problem token and its position. Note whether the error came from an INSERT/UPDATE, a cast in a SELECT, or an ALTER TABLE.
  2. Reproduce it in isolation. Run the smallest version of the failing statement, for example SELECT '{"a":1,}'::jsonb;. If that fails, the literal is the problem. If it succeeds, the problem is in the data being passed in, not in your SQL syntax.
  3. Find the bad rows when converting a column. Before altering a text column, test every value. A safe pattern is SELECT id, col FROM t WHERE col IS NOT NULL AND NOT (col ~ '^\s*[\{\[]'); to find values that do not even start like JSON, then attempt a cast inside a block that catches errors. In psql you can wrap the cast in a DO block with an EXCEPTION handler and log the failing primary key. This is more reliable than guessing from the error message alone.
  4. Check the usual culprits. Single quotes instead of double quotes around keys and strings, trailing commas before a closing brace or bracket, unquoted keys, comments, NaN or Infinity, Python-style True/False/None, escaped characters that are not valid JSON escapes, and empty strings where JSON is expected. An empty string is not valid JSON; use NULL instead.
  5. Decide whether to fix or reject the data. If the text is meant to be JSON, correct it at the source (the application, the import file or the ETL job) and re-run the load. If the column is optional, set bad values to NULL. Do not silently replace bad data with an empty object unless the application expects that.
  6. Validate before you convert. Once the data is clean, confirm with a query that casts every row, for example SELECT count(*) FROM t WHERE col IS NOT NULL AND col::jsonb IS NOT NULL;. If this returns without error, the ALTER will succeed.
  7. Run the conversion inside a transaction. Use BEGIN; ALTER TABLE t ALTER COLUMN col TYPE jsonb USING col::jsonb; COMMIT; so a failure leaves the table unchanged. On large tables this takes an exclusive lock and rewrites the table, so plan it for a quiet period.
  8. Fix application-side inserts. If the error comes from an app, log the exact string before it is sent. Most drivers pass strings through, so the bug is usually in serialization: double-encoding (a JSON string containing JSON text), manual string concatenation, or a library that emits non-standard output. Use the driver's native JSON support where available.
  9. Re-test the original statement with the corrected value and confirm the row is stored. Query it back with SELECT col, jsonb_typeof(col) FROM t WHERE id = ...; to verify it is a real JSON value, not a quoted string.

Common Mistakes

  • Assuming the error is a server bug. It is input validation; PostgreSQL is doing what it should.
  • Using single quotes for JSON keys. JSON requires double quotes, and inside SQL you escape them or use dollar quoting: $json${"a": 1}$json$.
  • Storing a JSON document as a JSON string. "{\"a\":1}" is valid JSON (a string), but it is not an object. Check with jsonb_typeof.
  • Converting a column without checking for empty strings or whitespace-only values.
  • Running ALTER TABLE on a busy production table without considering the lock and rewrite time.
  • Fixing rows by hand but leaving the application or import job that produced them unchanged, so the error returns on the next load.

Tips

  • Use jsonb rather than json for new columns: it validates on input, supports indexing and is generally the better default.
  • Validate JSON at the application boundary before it reaches the database, and return a clear validation message to the caller.
  • Keep a staging table of raw text, load into it first, then move validated rows into the typed table. Bad rows stay in staging for inspection.
  • Use dollar quoting for large JSON literals in SQL scripts to avoid escaping every double quote.
  • Test conversions on a copy of the table or a recent backup before touching production.

Troubleshooting

If the error persists after you fix the obvious row, the value may be arriving from a different code path than you think. Add logging on the application side and compare the logged string with what the database receives. If the error only appears in a batch job, check the batch's encoding and line endings; a byte-order mark or a smart quote copied from a document will fail validation.

If the error appears during ALTER TABLE, roll back and re-run the validation query. If it appears only for some users, check whether their client library serializes differently. If you cannot find the row, wrap the cast in a PL/pgSQL block with an EXCEPTION handler that records the primary key and the SQLSTATE, then run it over the table. If the table is very large, do the check in batches by primary key range to avoid long transactions.

If you are unsure whether a value is valid, test it in a scratch query first: SELECT $json$...$json$::jsonb;. Never delete rows to make an error go away until you have exported the bad values; they often reveal a bug in the producer.

Frequently Asked Questions

What does SQLSTATE 22032 mean exactly?

It is the invalid_json_text class error, raised when a string cannot be parsed as JSON. The message detail usually names the offending token.

Is an empty string valid JSON?

No. An empty string is not a JSON document. Use NULL for "no value", or store a valid document such as {} if the application expects an object.

Does this error affect json and jsonb equally?

Both types validate input, so both raise 22032 for malformed text. jsonb also normalizes the document, which can change key order and duplicate keys.

Can I disable JSON validation?

No. There is no setting that turns off JSON input validation. Store the value as text if you must keep unvalidated data, and validate later.

Why does the insert work in my client but fail in the app?

The app is probably double-encoding the value or building JSON by string concatenation. Log the exact string the driver sends and compare it with a known-good literal.

Will ALTER TABLE with USING col::jsonb lock the table?

Yes, it takes an exclusive lock and rewrites the table, so plan it for a maintenance window and test on a copy first.