COPY Loads JSONL Into A JSONB Column

COPY ingests JSONL line by line into a jsonb column, keeping nested structure intact where row-wise CSV parsing would flatten or fail.

SqlFile Upload

Code

snippet
CREATE TABLE webhook_events (
    payload jsonb NOT NULL
);

-- JSONL:一行一个 JSON 对象,整行灌进 jsonb 列,嵌套结构原样保留
COPY webhook_events (payload) FROM STDIN WITH (FORMAT text);
{"event":"checkout","cart":["sku-1","sku-2"],"total":42.5}
{"event":"refund","order_id":9812}
{"event":"login","user":"ada","ip":"10.0.0.9"}
\.

-- 单列 text 格式没有分隔符问题:数组与对象不会像 CSV 那样被打散
SELECT
    payload->>'event'             AS event,
    payload->'cart'               AS cart,
    payload->>'total'             AS total,
    jsonb_typeof(payload->'cart') AS cart_kind
FROM webhook_events
ORDER BY event;

-- 复核每一行都是合法 JSON 对象:坏行在 COPY 阶段就整体失败
SELECT count(*) AS object_rows
FROM webhook_events
WHERE jsonb_typeof(payload) = 'object';

What the code does

The file runs SELECT / CREATE statements, touching stdin and webhook_events.

Concretely, the SQL combines: a WHERE clause that keeps only the rows a statement is meant to touch; COUNT aggregation; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns.

Applying it

Run the statement against the stdin table.

Statements that matter

SELECT count(*) AS object_rows
FROM webhook_events
WHERE jsonb_typeof(payload) = 'object';
COPY webhook_events (payload) FROM STDIN WITH (FORMAT text);
CREATE TABLE webhook_events (
    payload jsonb NOT NULL
);

Interactive Tools for This Topic

FAQ

What objects does the SQL involve?
`stdin`, `webhook_events`.