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.

SqlData Integrity

Code

snippet
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

FAQ

Which tables does this file reference?
`events`.