SQL/JSON JSON_OBJECT And JSON_ARRAY Rules
Build JSON payloads with PostgreSQL 16 JSON_OBJECT and JSON_ARRAY, handling NULL ON NULL vs ABSENT ON NULL defaults and WITH UNIQUE KEYS.
Code
CREATE TEMP TABLE sku_labels (
sku text PRIMARY KEY
);
INSERT INTO sku_labels VALUES ('kbd-1'), ('amp-2');
-- Note the opposite defaults in SQL/JSON (PostgreSQL 16+):
-- JSON_OBJECT defaults to NULL ON NULL; JSON_ARRAY defaults to ABSENT ON NULL
SELECT
JSON_OBJECT('user' VALUE 'ada', 'note' VALUE NULL) AS obj_keeps_null,
JSON_OBJECT('user' VALUE 'ada', 'note' VALUE NULL ABSENT ON NULL RETURNING jsonb) AS obj_drops_null,
JSON_ARRAY('a', NULL, 'b') AS arr_drops_null,
JSON_ARRAY('a', NULL, 'b' NULL ON NULL RETURNING jsonb) AS arr_keeps_null;
-- WITH UNIQUE KEYS enforces distinct keys; subquery form builds an ordered JSON array
SELECT
JSON_OBJECT('env': 'prod', 'region': 'us-east' WITH UNIQUE KEYS RETURNING jsonb) AS meta,
JSON_ARRAY(SELECT sku FROM sku_labels ORDER BY sku RETURNING jsonb) AS sorted_skus;Logic trace — SQL/JSON JSON_OBJECT And JSON_ARRAY Rules
SELECT / INSERT / CREATE statements share the script, touching sku_labels.
sku_labels constructs temporary session tables right inside the SQL file itself so zero prior migrations are required and cleanup completes at session end.
Breaking the statements into their working parts: an ORDER BY that fixes the output order; a RETURNING clause that hands the affected rows back to the caller; a PRIMARY KEY that enforces row identity; UNIQUE constraints that keep duplicate values out.
Using it
It carries its own setup: the session-local tables in play (sku_labels) come from the file’s statements — run the entire file against a disposable database.
Key statements
SELECT
JSON_OBJECT('env': 'prod', 'region': 'us-east' WITH UNIQUE KEYS RETURNING jsonb) AS meta,
JSON_ARRAY(SELECT sku FROM sku_labels ORDER BY sku RETURNING jsonb) AS sorted_skus;
SELECT
JSON_OBJECT('user' VALUE 'ada', 'note' VALUE NULL) AS obj_keeps_null,
JSON_OBJECT('user' VALUE 'ada', 'note' VALUE NULL ABSENT ON NULL RETURNING jsonb) AS obj_drops_null,
JSON_ARRAY('a', NULL, 'b') AS arr_drops_null,
JSON_ARRAY('a', NULL, 'b' NULL ON NULL RETURNING jsonb) AS arr_keeps_null;
CREATE TEMP TABLE sku_labels (
sku text PRIMARY KEY
);
Interactive Tools for This Topic
FAQ
- Name the tables involved in this file.
- `sku_labels` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.