DuckDB Extension
JSON Schema
Validate JSON documents against a JSON Schema in DuckDB SQL. Check required fields and value types, or fill in defaults defined by your schema.
On this page
The DuckDB 2.0 build validates drafts 4, 6, 7, 2019-09 and 2020-12 (2020-12 when $schema is absent), asserts format, and adds json_schema_is_valid and json_schema_errors. Some documents that the draft-07-only validator accepted are now rejected. See Changes in the DuckDB 2.0 release.
Sample data for the examples
Each browser example starts with these sample tables; sample files are shared across examples on this page. Run this setup first when trying the examples in your own DuckDB session.
-- Concrete source data for validation, defaults, and quarantine examples.
-- Author-blessed schema-registry recipe (no bind variable).
CREATE OR REPLACE TABLE schema_registry AS
SELECT * FROM (VALUES
(
'events.v3',
1,
'{"$schema": "https://json-schema.org/draft-07/schema", "type": "object", "properties": {"id": {"type": "integer"}}}'::JSON
),
(
'events.v2',
1,
'{"$schema": "https://json-schema.org/draft-07/schema", "type": "object", "properties": {"id": {"type": "string"}}}'::JSON
)
) t(name, version, definition);
-- Source / sink / quarantine tables for the validation-and-routing recipes.
-- Payloads are intentionally varied — some valid against a typical "object
-- with id" schema, some not — so the documented TRY wrapper produces both valid and invalid rows.
CREATE OR REPLACE TABLE events AS
SELECT * FROM (VALUES
(1, '{"id": 1, "type": "click", "ts": "2026-04-28T12:00:00Z"}'::JSON),
(2, '{"id": 2, "type": "view"}'::JSON),
(3, '{"id": "not-a-number", "type": "click"}'::JSON),
(4, '{"type": "missing-id"}'::JSON),
(5, '{}'::JSON)
) t(row_num, payload);
CREATE OR REPLACE TABLE events_raw AS
SELECT * FROM events;
CREATE OR REPLACE TABLE events_clean (
row_num INTEGER,
payload JSON
);
CREATE OR REPLACE TABLE events_quarantine (
row_num INTEGER,
payload JSON
);
-- Local JSON input for the file-ingestion example.
COPY (SELECT * FROM (VALUES (1, 'Alice'), (2, 'Bob')) AS people(id, name))
TO 'events.json' (FORMAT JSON, ARRAY true);
Check that JSON documents follow an agreed structure
A JSON Schema describes a document’s expected fields, types, and constraints. DuckDB can read JSON with different shapes; this extension adds an explicit check against the contract you choose.
Use it to check API payloads or incoming records before further processing. The DuckDB 2.0 build supports JSON Schema drafts 4 through 2020-12 and adds boolean and structured-error functions; the Haybarn 1.5 build targets draft-07. Both can apply schema-defined defaults.
Example
Check two JSON documents
The schema requires an integer id. The first document passes; the second has a string where an integer is required. All sample data is included.
Tested with DuckDB 1.5.6. Browser examples use Haybarn-Wasm 2.0.0-rc12.
SET allow_extension_repositories = 'allowed';
CREATE EXTENSION REPOSITORY IF NOT EXISTS query_farm
WITH PREFIX 'https://duckdb-extensions.query.farm';
INSTALL json_schema FROM query_farm;
LOAD json_schema FROM query_farm;
WITH schema AS (
SELECT '{
"type": "object",
"properties": {"id": {"type": "integer"}},
"required": ["id"]
}'::JSON AS definition
), events(row_num, payload) AS (
VALUES
(1, '{"id": 42}'::JSON),
(2, '{"id": "oops"}'::JSON)
)
SELECT row_num, payload,
COALESCE(
TRY(json_schema_validate(definition, payload)), false
) AS valid
FROM events CROSS JOIN schema
ORDER BY row_num;
SET allow_extension_repositories = 'allowed';
CREATE EXTENSION REPOSITORY IF NOT EXISTS query_farm
WITH PREFIX 'https://haybarn-extensions.query.farm';
INSTALL json_schema FROM query_farm;
LOAD json_schema FROM query_farm;
WITH schema AS (
SELECT '{
"type": "object",
"properties": {"id": {"type": "integer"}},
"required": ["id"]
}'::JSON AS definition
), events(row_num, payload) AS (
VALUES
(1, '{"id": 42}'::JSON),
(2, '{"id": "oops"}'::JSON)
)
SELECT row_num, payload,
COALESCE(
TRY(json_schema_validate(definition, payload)), false
) AS valid
FROM events CROSS JOIN schema
ORDER BY row_num;
INSTALL json_schema FROM community;
LOAD json_schema;
WITH schema AS (
SELECT '{
"type": "object",
"properties": {"id": {"type": "integer"}},
"required": ["id"]
}'::JSON AS definition
), events(row_num, payload) AS (
VALUES
(1, '{"id": 42}'::JSON),
(2, '{"id": "oops"}'::JSON)
)
SELECT row_num, payload,
COALESCE(
TRY(json_schema_validate(definition, payload)), false
) AS valid
FROM events CROSS JOIN schema
ORDER BY row_num;
Expected result
| row_num | payload | valid |
|---|---|---|
| 1 | {"id":42} | true |
| 2 | {"id":"oops"} | false |
Validation raises an error for a nonconforming document. TRY turns that error into NULL; COALESCE makes the result false. Validate a schema separately before using this pattern with your own data, because TRY also catches errors in the schema. In the DuckDB 2.0 build, json_schema_is_valid(definition, payload) returns the boolean directly.
Common tasks
- Check the schema itself Catch schema errors before validating a batch of documents.
- Validate a JSON column Count valid and invalid documents in an existing table.
- Apply default values Fill missing fields using defaults declared in the schema.
- Read JSON files into DuckDB See how JSON loading and schema validation fit together.
Deep Dive
Technical Details
Validation behavior
json_schema_validate returns TRUE for a valid document and raises an error for an invalid one. In the DuckDB 2.0 build, json_schema_is_valid returns TRUE/FALSE instead, and json_schema_errors returns every failure as a LIST(STRUCT(path, keyword, message)), where path is a JSON Pointer into the document. All functions raise an error for an invalid schema, so a broken contract is never mistaken for bad data. On the Haybarn 1.5 build, check the schema itself with json_schema_validate_schema before wrapping document validation in TRY.
The $schema keyword selects the draft. The DuckDB 2.0 build supports drafts 4, 6, 7, 2019-09 and 2020-12, uses 2020-12 when $schema is absent, and rejects an unknown $schema. The Haybarn 1.5 build targets draft-07 only: it ignores newer keywords such as prefixItems or unevaluatedProperties. External files and HTTP references are never resolved; include referenced definitions (for example under $defs) in the schema document.
Architecture
Internally this is a thin DuckDB scalar-function wrapper around a C++ JSON Schema library: jsoncons in the DuckDB 2.0 build, pboettch/json-schema-validator with nlohmann/json in the Haybarn 1.5 build. Both schema and data are passed as DuckDB JSON values (or struct literals, or strings cast with ::JSON). There is no ATTACH, no secret type, no network call — the validator runs locally against the in-query schema.
Six scalar functions cover the surface (json_schema_is_valid and json_schema_errors are DuckDB 2.0 build only):
| Group | Functions | Returns |
|---|---|---|
| Validate | json_schema_validate, json_schema_validate_schema, json_schema_is_valid |
BOOLEAN |
| Validate | json_schema_errors |
LIST(STRUCT(path, keyword, message)) |
| Enrich | json_schema_patch, json_schema_update |
JSON |
Schema features include type validation (string, number, integer, boolean, array, object, null), required, properties, numeric minimum / maximum / multipleOf, string minLength / maxLength / pattern / format, array minItems / maxItems / uniqueItems, combinators and local $ref, plus (DuckDB 2.0 build) the 2019-09/2020-12 vocabulary such as prefixItems, unevaluatedProperties, dependentRequired and $defs, and the default keyword used by json_schema_patch and json_schema_update.
Pairs with DuckDB’s JSON support
Schema-side validation is one piece; the rest of the JSON pipeline is plain DuckDB. Read JSON files with read_json_auto, pull out fields with json_extract_*, or cast strings with ::JSON — and feed any of those into json_schema_validate. See DuckDB JSON overview for the surrounding toolkit.
Compared to alternatives
- DuckDB
CHECKconstraints — if your data has a fixed shape, modeling it as proper columns plusCHECKis faster, clearer, and gives you better error messages. Reach for JSON Schema when the payload is genuinely contract-defined JSON and the storage stays opaque. - Application-layer validators (ajv / Pydantic / jsonschema) — these offer custom formats, remote
$refloading and ECMAScript regular expressions. Pair them at the API boundary; use this extension as the SQL-side gate inside DuckDB so the database doesn’t depend on a Python service to enforce its contracts. - Manual SQL predicates — handcrafted
WHEREs overjson_extract_*get unwieldy fast for non-trivial schemas. Pointingjson_schema_validateat a versioned schema file keeps the contract in one place.
Default-value enrichment
Use the schema’s declared default values to fill missing fields. json_schema_patch returns a JSON Patch (RFC 6902) array of add operations; json_schema_update applies them inline. Together they let you go from “incoming partial payload” to “fully populated record” in one SQL expression — no per-field COALESCE cascade, no application-layer enrichment code.
Changes in the DuckDB 2.0 release
The validator changed from pboettch/json-schema-validator (draft-07 only) to jsoncons. Some documents that earlier builds accepted are now rejected, and some schemas behave differently:
$schemais honoured. Drafts 4, 6, 7, 2019-09 and 2020-12 are supported. Earlier builds evaluated everything as draft-07 and silently ignored newer keywords (prefixItems,unevaluatedProperties,dependentRequired,$defsreferences, …), so non-conforming documents passed. An unknown$schemais now an error.- Schemas without
$schemause 2020-12 (earlier builds: draft-07). A draft-07 schema that uses array-formitemsfor tuples should declare"$schema": "http://json-schema.org/draft-07/schema#". formatis validated. Earlier builds raised “a format checker was not provided” for any schema usingformat.- Regular expressions use RE2.
patternandpatternPropertiesrun in linear time, so a hostile pattern cannot hang or crash DuckDB, but lookaround ((?=,(?!) and backreferences are rejected as schema errors. - Error messages from
json_schema_validate,json_schema_patchandjson_schema_updatelist up to five failing locations (JSON Pointer + message) and no longer echo the whole document.
Also new in the DuckDB 2.0 build:
- New functions:
json_schema_is_valid(BOOLEAN, noTRYneeded) andjson_schema_errors(structured per-keyword report). - Performance: each schema is compiled once per thread and reused for every row, instead of being parsed and compiled for every row.
- Limits: schemas and documents nested more than 256 levels are rejected, and deep recursion through
$refraises an error before it can exhaust the thread’s stack. - Remote
$refs are still not loaded (no network or file access); the error now reads “Don’t know how to load JSON Schema …”.
Reference
Extension Contents
Quick reference to all available functions and settings organized by category.
| Name | Type | Description |
|---|---|---|
|
Enrich
Default-value handling. |
||
| json_schema_patch() | Object type: Scalar function |
Compute the JSON Patch (RFC 6902) diff that would bring json_data into conformance with the default values declared by the schema.
|
| json_schema_update() | Object type: Scalar function |
Apply the schema's default values inline.
|
|
Validate
Conformance checks. |
||
| json_schema_errors() | Object type: Scalar function |
Return every validation error of a JSON value against a JSON Schema as a structured list: where in the document it failed (path), which schema keyword failed (keyword) and a readable message.
|
| json_schema_is_valid() | Object type: Scalar function | Return whether a JSON value conforms to a JSON Schema. |
| json_schema_validate() | Object type: Scalar function | Validate a JSON value against a JSON Schema. |
| json_schema_validate_schema() | Object type: Scalar function | Check that a JSON Schema compiles. |
No extension contents match that search.
API Reference
Function Reference
Practical Examples
Cookbook
Real-world recipes and patterns for common use cases.
Validate one document
SELECT json_schema_validate('{ "$schema": "https://json-schema.org/draft-07/schema", "type": "object", "properties": { "id": {"type": "integer"}, "name": {"type": "string"} }, "required": ["id"]}', {'id': 5, 'name': 'George'}) AS valid;-- TRUEThe schema document follows the JSON Schema specification. See json_schema_validate.
Filter with a boolean (DuckDB 2.0 build)
json_schema_is_valid returns FALSE for a nonconforming document instead of raising, so no TRY is needed — and an invalid schema still raises, so it can’t hide as “invalid data”:
SELECT row_num, payloadFROM eventsWHERE json_schema_is_valid('{"type":"object","properties":{"id":{"type":"integer"}},"required":["id"]}', payload)ORDER BY row_num;Report why rows fail (DuckDB 2.0 build)
json_schema_errors returns one {path, keyword, message} struct per failure, with path as a JSON Pointer into the document:
SELECT row_num, e.path, e.keyword, e.messageFROM events, unnest(json_schema_errors('{"type":"object","properties":{"id":{"type":"integer"}},"required":["id"]}', payload)) AS t(e)ORDER BY row_num;Store the list next to quarantined rows to keep the reason with the data:
INSERT INTO events_quarantineSELECT row_num, payloadFROM events_rawWHERE len(json_schema_errors('{"type":"object","properties":{"id":{"type":"integer"}},"required":["id"]}', payload)) > 0;Use 2020-12 keywords (DuckDB 2.0 build)
$schema picks the draft (2020-12 when omitted). Tuple validation with prefixItems, closed objects with unevaluatedProperties, and format assertions are all enforced:
SELECT json_schema_is_valid('{"prefixItems": [{"type": "string"}, {"type": "integer"}]}', '["a", 1]') AS tuple_ok, json_schema_is_valid('{"properties": {"a": {}}, "unevaluatedProperties": false}', '{"a": 1, "b": 2}') AS closed_ok, json_schema_is_valid('{"format": "email"}', '"not an email"') AS email_ok;-- true, false, falseValidate a column
Most real workloads point validation at a JSON column instead of a literal:
SET VARIABLE event_schema = '{"$schema":"https://json-schema.org/draft-07/schema","type":"object","properties":{"id":{"type":"integer","default":5},"name":{"type":"string"}},"required":["id"]}';
SELECT COUNT(*) AS total, COUNT(*) FILTER (WHERE COALESCE(TRY(json_schema_validate(getvariable('event_schema'), payload)), false)) AS valid, COUNT(*) FILTER (WHERE NOT COALESCE(TRY(json_schema_validate(getvariable('event_schema'), payload)), false)) AS invalidFROM events;json_schema_validate returns TRUE for valid data and raises an error for invalid data. TRY turns errors into NULL; COALESCE(..., false) counts errors and SQL NULL inputs as invalid. Validate the schema once outside TRY before processing rows, because TRY also catches invalid-schema errors. Each runnable example sets event_schema to a concrete schema; replace it with the schema your application uses.
Lint the schema before deploying
Before pushing a schema to production, verify it’s well-formed:
SELECT json_schema_validate_schema('{ "$schema": "https://json-schema.org/draft-07/schema", "type": "object", "properties": { "id": { "type": "integer" } }}') AS schema_ok;-- TRUEjson_schema_validate_schema checks whether the validator can load a schema, raising on errors. It is not exhaustive meta-schema validation and may accept unsupported keyword values. To find entries that fail to load without aborting the registry scan:
SELECT name, versionFROM schema_registryWHERE NOT COALESCE(TRY(json_schema_validate_schema(definition)), false);Quality-gate filter at ingest
Reject non-conforming payloads at the boundary; tee the rest into a quarantine table for review:
SET VARIABLE event_schema = '{"$schema":"https://json-schema.org/draft-07/schema","type":"object","properties":{"id":{"type":"integer","default":5},"name":{"type":"string"}},"required":["id"]}';
INSERT INTO events_cleanSELECT * FROM events_rawWHERE COALESCE(TRY(json_schema_validate(getvariable('event_schema'), payload)), false);SET VARIABLE event_schema = '{"$schema":"https://json-schema.org/draft-07/schema","type":"object","properties":{"id":{"type":"integer","default":5},"name":{"type":"string"}},"required":["id"]}';
INSERT INTO events_quarantineSELECT * FROM events_rawWHERE NOT COALESCE(TRY(json_schema_validate(getvariable('event_schema'), payload)), false);Compute a defaults patch
Given a schema with default values declared, json_schema_patch returns the JSON Patch (RFC 6902) add operations needed to fill in the missing fields:
SELECT json_schema_patch('{ "$schema": "https://json-schema.org/draft-07/schema", "type": "object", "properties": { "id": {"type": "integer", "default": 5}, "name": {"type": "string"} }}', {'name': 'George'}) AS patch;-- [{"op":"add","path":"/id","value":5}]Useful when you want to log or audit which fields were synthesized, or when the same diff has to apply to multiple downstream representations.
Apply defaults inline
When you want enriched JSON rather than the diff, reach for json_schema_update instead:
SELECT json_schema_update('{ "$schema": "https://json-schema.org/draft-07/schema", "type": "object", "properties": { "id": {"type": "integer", "default": 5}, "name": {"type": "string"} }}', {'name': 'George'}) AS updated;-- {"id":5,"name":"George"}Build a clean enriched table in one step — validate, then enrich:
SET VARIABLE event_schema = '{"$schema":"https://json-schema.org/draft-07/schema","type":"object","properties":{"id":{"type":"integer","default":5},"name":{"type":"string"}},"required":["id"]}';
CREATE TABLE events_enriched ASSELECT json_schema_update(getvariable('event_schema'), payload) AS payloadFROM events_rawWHERE COALESCE(TRY(json_schema_validate(getvariable('event_schema'), payload)), false);Validate JSON files on ingest
Pair with DuckDB’s read_json_auto for file-based inputs:
SET VARIABLE event_schema = '{"$schema":"https://json-schema.org/draft-07/schema","type":"object","properties":{"id":{"type":"integer","default":5},"name":{"type":"string"}},"required":["id"]}';
SELECT *FROM read_json_auto('events.json') AS eventWHERE COALESCE(TRY(json_schema_validate(getvariable('event_schema'), to_json(event))), false);For records arriving as already-typed JSON columns, pass the column directly without the to_json wrap.
Use a schema parameter
Keep the schema out of query text by binding it as a SQL variable — handy when the same query runs against different contracts:
SET VARIABLE event_schema = (SELECT definition FROM schema_registry WHERE name = 'events.v3');SELECT json_schema_validate_schema(getvariable('event_schema'));
SELECT COUNT(*) AS validFROM eventsWHERE COALESCE(TRY(json_schema_validate(getvariable('event_schema'), payload)), false);Platform Support
Compatibility
Extension availability may vary by platform and DuckDB version. Check below to ensure this extension supports your environment before installation.
Quick Facts
Platforms
DuckDB 2.0.0
- Linux x86_64aarch64
- Linux (musl) Not available
- macOS Apple Silicon
- Windows x86_64x86_64 (MinGW)
- WASM Not available
Compiled binary sizes
| Platform | Architecture | Size |
|---|---|---|
| Linux | x86_64 | 4.18 MB |
| Linux | aarch64 | 3.53 MB |
| macOS | Apple Silicon | 2.97 MB |
| Windows | x86_64 | 10.34 MB |
| Windows | x86_64 (MinGW) | 18.01 MB |
Compressed download sizes for the release shown above.
DuckDB & Haybarn
Release calendar- DuckDB v2.0.0 Query.Farm repository Supported
- Haybarn v1.5.6 Built-in community repository Supported
Browser examples use Haybarn-Wasm 2.0.0-rc12.
Checked .
Learn and explore
Tutorials and articles
Writing about JSON Schema: how it works, what changed, and why.
-
JSON Schema for DuckDB 2.0: validate a column without losing the bad rows
JSON Schema for DuckDB 2.0 adds boolean validation, structured errors, and support through draft 2020-12, with explicit format checks and safer regular expressions.
-
Tutorial · 6 min ·
Validate Incoming JSON with DuckDB and JSON Schema
Check required fields, value types, and constraints in JSON with Query.Farm’s JSON Schema extension. Keep valid and rejected records visible in a runnable SQL lesson.