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.
Code
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
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 Column AnalyzerProfile every CSV column with inferred types, empty-cell counts, unique values, and numeric min and max ranges.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.
FAQ
- What objects does the SQL involve?
- `stdin`, `webhook_events`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.