IS JSON Predicate Validates JSON Columns
Constrain a jsonb column with the IS JSON OBJECT predicate and test VALUE, ARRAY, SCALAR, and unique-key variants.
Code
CREATE TABLE events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
payload jsonb NOT NULL,
CONSTRAINT payload_is_object CHECK (payload IS JSON OBJECT)
);
INSERT INTO events (payload)
VALUES ('{"type":"click","x":12}'), ('{"type":"view","x":4}');
SELECT id,
payload IS JSON AS valid_json,
payload IS JSON OBJECT AS is_object
FROM events;
-- IS JSON also validates text before casting it
SELECT '{"a":1}'::text IS JSON AS text_ok,
'not json'::text IS JSON AS text_bad,
'[1,2]'::text IS JSON ARRAY AS is_array,
'"hello"'::text IS JSON SCALAR AS is_scalar;
-- WITH UNIQUE KEYS rejects duplicate object keys
SELECT '{"a":1,"a":2}'::text IS JSON WITH UNIQUE KEYS AS unique_keys;How it works
Several statements share this file — SELECT / INSERT / CREATE, with events among the objects involved.
Breaking the statements into their working parts: a CHECK constraint that rejects out-of-domain values at write time; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; UNIQUE constraints that keep duplicate values out; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.
Applying it
Point it at the events table.
Statements that matter
SELECT '{"a":1,"a":2}'::text IS JSON WITH UNIQUE KEYS AS unique_keys;
SELECT '{"a":1}'::text IS JSON AS text_ok,
'not json'::text IS JSON AS text_bad,
'[1,2]'::text IS JSON ARRAY AS is_array,
'"hello"'::text IS JSON SCALAR AS is_scalar;
CREATE TABLE events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
payload jsonb NOT NULL,
CONSTRAINT payload_is_object CHECK (payload IS JSON OBJECT)
);
Interactive Tools for This Topic
Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.
FAQ
- Which tables does this file reference?
- `events`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.