JSONPostgreSQL only

JSONB_OBJECT_KEYS

Returns the keys of a JSON object — one row per key.

Syntax

JSONB_OBJECT_KEYS(<json object>)

Only the names of top-level keys, without values. Handy for finding out which fields actually occur in a JSON column, or checking that nothing extra has turned up.

Data for the examples

employees

namedepartmentsalarybonusphone
Emmabackend1200300+44 7700 900123
Liambackend1000NULLNULL
Oliviafrontend1350150+44 7700 900456
Noahfrontend950NULL+44 7700 900789
Sophiadesign1200200NULL

These tables already exist in the sandbox — the examples below use them. Want to try this in your own database? Copy the SQL.

The keys of an object
SELECT JSONB_OBJECT_KEYS('{"color": "black", "storage": 256, "wireless": true}') AS key;
key
color
storage
wireless
How many keys
SELECT COUNT(*) AS key_count
FROM JSONB_OBJECT_KEYS('{"color": "black", "storage": 256, "wireless": true}');
key_count
3
Which fields a table record has
SELECT JSONB_OBJECT_KEYS(TO_JSONB(e)) AS column_name
FROM employees e
WHERE e.name = 'Emma';
column_name
name
bonus
phone
salary
department

TO_JSONB(e) turns a table row into an object, and JSONB_OBJECT_KEYS lists its keys — that is, the column names.

Watch out

Top level only: the keys of nested objects aren't included.

For an array — the error cannot call jsonb_object_keys on an array.

The keys don't come in the order they were written: jsonb stores them ordered, shorter ones first.

To check a single key, the ? operator is simpler: data ? 'color' gives true or false.