jsonb_populate_record Maps JSON To Rows

Map jsonb documents onto a composite type with jsonb_populate_record, including missing keys and ignored extras.

SqlData Integrity

Code

snippet
CREATE TYPE contact AS (
  name text,
  email text,
  age int
);

CREATE TABLE leads (
  id int PRIMARY KEY,
  payload jsonb NOT NULL
);

INSERT INTO leads (id, payload)
VALUES
  (1, '{"name":"Ada","email":"[email protected]","age":36,"source":"web"}'),
  (2, '{"name":"Grace","email":"[email protected]"}');

SELECT id,
       (jsonb_populate_record(NULL::contact, payload)).*
FROM leads
ORDER BY id;

-- Missing keys become NULL; unknown keys are ignored.
SELECT (jsonb_populate_record(
  NULL::contact,
  '{"age":"41","email":"[email protected]"}'::jsonb
)).*;

Inside the snippet

Several statements share this file — SELECT / INSERT / CREATE, with leads among the objects involved.

The SQL constructs in play: an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Using it

The leads table is the working surface here.

Key statements

INSERT INTO leads (id, payload)
VALUES
(1, '{"name":"Ada","email":"[email protected]","age":36,"source":"web"}'),
(2, '{"name":"Grace","email":"[email protected]"}');
SELECT (jsonb_populate_record(
NULL::contact,
'{"age":"41","email":"[email protected]"}'::jsonb
)).*;
SELECT id,
(jsonb_populate_record(NULL::contact, payload)).*
FROM leads
ORDER BY id;

Interactive Tools for This Topic

FAQ

Which objects does the SQL touch?
`leads`.