jsonb each text Unpack Pairs

Turn one JSON object per row into key/value pairs with jsonb_each_text, then filter or aggregate pairs that columns cannot express.

SqlData Integrity

Code

snippet
-- 每行一个 JSON 对象:字段名不定,无法直接用列筛选
CREATE TABLE event_payloads (
    id      serial PRIMARY KEY,
    payload jsonb NOT NULL
);

INSERT INTO event_payloads (payload) VALUES
    ('{"browser": "firefox", "plan": "pro"}'),
    ('{"browser": "safari",  "plan": "free"}'),
    ('{"browser": "chrome",  "plan": "pro", "beta": "on"}');

-- jsonb_each_text 把对象展开成 key/value 行
SELECT e.id, pair.key, pair.value
FROM event_payloads e,
     jsonb_each_text(e.payload) AS pair(key, value)
ORDER BY e.id, pair.key;

-- 展开后就能做定列表达不了的条件:任意键命中某值
SELECT e.id, e.payload
FROM event_payloads e,
     jsonb_each_text(e.payload) AS pair(key, value)
WHERE pair.value = 'pro';

DROP TABLE event_payloads;

How it works

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

Mechanically, the statements are built from: 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.

Applying it

Run the statement against the event_payloads table.

Statements that matter

SELECT e.id, e.payload
FROM event_payloads e,
jsonb_each_text(e.payload) AS pair(key, value)
WHERE pair.value = 'pro';
INSERT INTO event_payloads (payload) VALUES
('{"browser": "firefox", "plan": "pro"}'),
('{"browser": "safari",  "plan": "free"}'),
('{"browser": "chrome",  "plan": "pro", "beta": "on"}');
SELECT e.id, pair.key, pair.value
FROM event_payloads e,
jsonb_each_text(e.payload) AS pair(key, value)
ORDER BY e.id, pair.key;

Interactive Tools for This Topic

FAQ

Which tables does this file reference?
`event_payloads` — referenced directly, no join needed.