jsonb_strip_nulls Removes Null Object Fields
Remove null-valued object fields recursively with jsonb_strip_nulls and confirm that array elements keep their shape.
Code
CREATE TABLE profiles (
id int PRIMARY KEY,
document jsonb NOT NULL
);
INSERT INTO profiles (id, document)
VALUES
(1, '{"name":"Ada","nickname":null,"address":{"city":null,"zip":"10115"},"tags":[null]}'),
(2, '{"name":"Grace","nickname":"G","address":{"city":"Arlington","zip":null}}');
SELECT id, jsonb_strip_nulls(document) AS compact
FROM profiles
ORDER BY id;
-- Null object fields are removed recursively; arrays keep their shape.
SELECT jsonb_strip_nulls('{"a":null,"b":{"c":null,"d":1},"e":[null]}'::jsonb) AS result;
SELECT document ? 'nickname' AS had_nickname_key,
jsonb_strip_nulls(document) ? 'nickname' AS keeps_nickname_key
FROM profiles
WHERE id = 1;What the code does
Several statements share this file — SELECT / INSERT / CREATE, with profiles among the objects involved.
The pieces that do the work: a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Using it
Run the statement against the profiles table.
Key statements
SELECT document ? 'nickname' AS had_nickname_key,
jsonb_strip_nulls(document) ? 'nickname' AS keeps_nickname_key
FROM profiles
WHERE id = 1;
INSERT INTO profiles (id, document)
VALUES
(1, '{"name":"Ada","nickname":null,"address":{"city":null,"zip":"10115"},"tags":[null]}'),
(2, '{"name":"Grace","nickname":"G","address":{"city":"Arlington","zip":null}}');
SELECT jsonb_strip_nulls('{"a":null,"b":{"c":null,"d":1},"e":[null]}'::jsonb) AS result;
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 appear in this script?
- `profiles`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.