DuckDB Extension
JSONata
Query and reshape JSON values in DuckDB with JSONata expressions. Select nested fields, filter arrays, and construct a new JSON object.
On this page
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.
-- Fixtures for the jsonata extension cookbook / technical-details / functions.json
-- examples. Each table has a JSON `payload` column with realistic shape.
-- Idempotent: uses CREATE OR REPLACE.
CREATE OR REPLACE TABLE contacts AS
SELECT * FROM (VALUES
(
1,
'{
"FirstName": "Fred",
"Surname": "Smith",
"Account": {"Name": "Firefly", "Tier": "gold"},
"Phone": [
{"type": "home", "number": "0203 544 1234"},
{"type": "mobile", "number": "077 7700 1234"}
],
"Orders": [
{"Quantity": 3, "UnitPrice": 12.50},
{"Quantity": 1, "UnitPrice": 40.00}
]
}'::JSON
),
(
2,
'{
"FirstName": "Jane",
"Surname": "Doe",
"Account": {"Name": "Acme", "Tier": "silver"},
"Phone": [
{"type": "home", "number": "0207 555 0100"},
{"type": "mobile", "number": "077 1234 5678"}
],
"Orders": [
{"Quantity": 2, "UnitPrice": 5.00}
]
}'::JSON
)
) AS t(contact_id, payload);
CREATE OR REPLACE TABLE orders AS
SELECT * FROM (VALUES
(
1001,
'{
"Order": {
"Product": [
{"Description": {"Colour": "red"}, "Price": 10.00, "Quantity": 2},
{"Description": {"Colour": "blue"}, "Price": 5.50, "Quantity": 4}
]
}
}'::JSON
),
(
1002,
'{
"Order": {
"Product": [
{"Description": {"Colour": "green"}, "Price": 7.25, "Quantity": 1}
]
}
}'::JSON
)
) AS t(order_id, payload);
CREATE OR REPLACE TABLE invoices AS
SELECT * FROM (VALUES
(
1,
'{
"items": [
{"id": "a", "status": "open", "amount": 250, "price": 250},
{"id": "b", "status": "closed", "amount": 90, "price": 90},
{"id": "c", "status": "open", "amount": 50, "price": 50}
]
}'::JSON
)
) AS t(invoice_id, payload);
CREATE OR REPLACE TABLE line_items AS
SELECT * FROM (VALUES
(
1,
'{
"items": [
{"id": "x", "price": 150},
{"id": "y", "price": 80},
{"id": "z", "price": 200}
]
}'::JSON
)
) AS t(line_item_id, payload);
Transform nested JSON with a dedicated expression language
JSONata is a language for selecting, filtering, aggregating, and reshaping JSON. The extension evaluates a JSONata expression against a JSON value in DuckDB and returns the transformed document.
It is useful when you need to traverse nested arrays or build a new object from several parts of a document. DuckDB’s built-in JSON operators already cover simple field extraction; JSONata gives you another way to express more involved transformations or reuse existing JSONata rules.
Example
Select a mobile number from JSON
The expression filters Phone by type and selects the number from the matching item.
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 jsonata FROM query_farm;
LOAD jsonata FROM query_farm;
SELECT jsonata(
'Phone[type="mobile"].number',
'{"Phone":[{"type":"home","number":"555-0100"},{"type":"mobile","number":"555-0199"}]}'
) AS mobile;
SET allow_extension_repositories = 'allowed';
CREATE EXTENSION REPOSITORY IF NOT EXISTS query_farm
WITH PREFIX 'https://haybarn-extensions.query.farm';
INSTALL jsonata FROM query_farm;
LOAD jsonata FROM query_farm;
SELECT jsonata(
'Phone[type="mobile"].number',
'{"Phone":[{"type":"home","number":"555-0100"},{"type":"mobile","number":"555-0199"}]}'
) AS mobile;
INSTALL jsonata FROM community;
LOAD jsonata;
SELECT jsonata(
'Phone[type="mobile"].number',
'{"Phone":[{"type":"home","number":"555-0100"},{"type":"mobile","number":"555-0199"}]}'
) AS mobile;
Expected result
| mobile |
|---|
| 555-0199 |
JSONata has its own expression syntax. Keep SQL quoting separate from the quotes used inside the JSONata expression and JSON document.
Common tasks
Deep Dive
Technical Details
What you can do with one query
The headline pattern — reshape a nested JSON column into a clean output object in a single SQL projection:
SELECT jsonata('{ "name": FirstName & " " & Surname, "mobile": Phone[type="mobile"].number, "lifetime": $sum(Orders.(Quantity * UnitPrice))}', payload) AS profileFROM contacts;One jsonata call replaces a stack of json_extract_string projections plus an unnest subquery for the order roll-up. The expression — array filter, object construction, and an aggregation function — stays in one string.
This extension exposes JSONata as a scalar SQL function — jsonata, in two arities — plus jsonata_validate for checking expression syntax. There is no ATTACH interface, no secrets, no I/O. The functions operate on JSON values DuckDB already has in memory.
It is the right tool when DuckDB’s native JSON functions get verbose — array predicate filters, object reshaping, multi-step transforms. It is not a JSON loader (use DuckDB’s read_json for that) and it does not register custom DuckDB UDFs as callables inside the JSONata expression.
Architecture
The extension is a C++ scalar UDF built on jsonata-cpp, a port of the JSONata reference implementation. Each call to jsonata takes a JSONata expression string and a JSON value, parses the expression into an AST, evaluates it against the document, and returns a JSON result. There is no network, no state carried from one row to the next, and no DuckDB type beyond the standard JSON type.
Parsed expressions are cached. When the expression argument is a SQL constant — by far the common case — the parser runs once per worker thread and the compiled program is reused for every row. In the DuckDB 2.0 build an expression column is cached too: each thread keeps its 32 most recently used expressions, so a table of a few dozen stored expressions isn’t re-parsed on every row. Per-row cost is dominated by the JSON walk plus operator application; deeply-nested documents and large arrays scale linearly with the data they touch.
The 3-arg form, jsonata(expr, json, bindings), takes a JSON object whose keys become $variable names inside the expression. This is how you pass per-query values — thresholds, ids, dates — into an otherwise static expression so the parse cache still applies.
When to reach for JSONata vs DuckDB native JSON
DuckDB ships a rich JSON function library — json_extract, json_extract_string, the ->/->> operators, json_structure, and a JSON data type. For one-field-one-path access these are the right call — vectorized, idiomatic SQL, no extra extension.
JSONata is the better fit when the path includes any of:
- Predicate filters on arrays.
Phone[type="mobile"].numberselects matching elements and projects in one step. The native equivalent isunnestplus a subquery with aWHEREclause. - Object reshaping. Construction expressions build a fresh JSON object literal — pull, rename, and compute fields together. The native equivalent is one
json_extract_stringper output field. - Embedded aggregation.
$sum,$count,$maxoperate on arrays inside the JSON document. The native equivalent leaves the JSON value, unnests, aggregates, and returns. - Higher-order array operations.
$map,$filter,$reducekeep transforms inline. The native equivalent is a lateral subquery.
Concrete contrast — selecting the mobile number from a contact’s Phone array:
-- DuckDB native: extract the array, unnest, filter, projectSELECT ( SELECT json_extract_string(p, '$.number') FROM unnest(json_extract(payload, '$.Phone')::JSON[]) AS t(p) WHERE json_extract_string(p, '$.type') = 'mobile' LIMIT 1) AS mobileFROM contacts;-- JSONata: one expressionSELECT jsonata('Phone[type="mobile"].number', payload) AS mobileFROM contacts;For a single field at a fixed path, native is simpler. The break-even is roughly “any predicate, any reshape, or more than two output fields.”
Compared to alternatives
- DuckDB native JSON (
->>,json_extract) — the right choice for simple field-by-field access. Stays simpler and avoids the extension entirely. Use JSONata when the expression starts to fan out across array predicates or object construction. jqoutside DuckDB — same general role for JSON, different language.jqis a separate process — file in, file out. JSONata-in-DuckDB keeps the transform inside the SQL plan, vectorized, joinable, andEXPLAIN-able alongside the rest of the query.- Application-side JSONata libraries (JS, Python, etc.) — the right call when the surrounding logic already lives in the app. Bringing JSONata into DuckDB matters when the JSON sits in a column and the rest of the pipeline is SQL — no row-format conversion, no result shuttling.
Iterating on expressions
JSONata expressions live inside SQL string literals, which makes them awkward to edit in place. The official JSONata exerciser takes a sample document and gives live results — the fastest loop for any non-trivial expression. The evaluator there matches what the extension runs, so once an expression is right in the exerciser it transfers unchanged into the SQL string.
Resource limits
The DuckDB 2.0 build bounds every evaluation, so a runaway expression fails the query instead of crashing or hanging DuckDB:
| Setting | Default | Effect |
|---|---|---|
jsonata_max_depth |
1000 |
Maximum evaluation depth, which bounds recursion in user-defined functions. Exceeding it raises JSONata evaluation exceeded the maximum evaluation depth of 1000. 0 removes the depth limit. |
jsonata_timeout_ms |
10000 |
Maximum wall-clock time of one evaluation (one row). Exceeding it raises JSONata evaluation timed out after … ms. 0 disables the timeout. |
SET jsonata_max_depth = 5000; -- deeper recursionSET jsonata_timeout_ms = 500; -- fail fast on slow expressionsIndependently of these settings:
- A running evaluation stops when the query is cancelled (Ctrl-C,
interrupt()). - A native stack guard, sized to the thread the query actually runs on, stops recursion before it can overflow the stack even with
jsonata_max_depth = 0. - JSON documents and bindings nested more than 1,000 levels deep, and expressions nested too deeply for the available stack, are rejected with an error before evaluation.
A tail-recursive loop such as ($f := function($x){ $f($x) }; $f(1)) never grows the stack, so only the timeout or cancellation stops it.
Regular expressions
In the DuckDB 2.0 build, JSONata regular expressions (/pattern/flags, and the patterns given to $match, $contains, $split and $replace) run on RE2, the same engine as DuckDB’s regexp_matches. Matching takes linear time, so no pattern can hang a query through catastrophic backtracking, and long subject strings are safe. The i (case-insensitive) and m (multiline: ^ and $ match at line breaks) flags are supported.
RE2 has no lookaround ((?=…), (?!…), (?<=…)) and no backreferences (\1). Patterns that use them fail with invalid regular expression.
Changes in the DuckDB 2.0 release
- Regular expressions use RE2. Lookaround and backreferences now raise
invalid regular expression, and themflag is honoured (earlier builds ignored it). See Regular expressions. - Evaluations are bounded. Expressions that run longer than
jsonata_timeout_ms(10 seconds by default) or recurse deeper thanjsonata_max_depth(1,000) now fail; raise or disable the settings for legitimately heavy expressions. See Resource limits. - JSON nested more than 1,000 levels deep is rejected.
Also new in the DuckDB 2.0 build:
- Crash fixes: non-terminating recursion, deeply nested JSON or expressions, and long regex subject strings used to crash DuckDB; they now raise errors, and a runaway evaluation can be cancelled.
- New function:
jsonata_validatechecks whether a string is a valid JSONata expression without evaluating it. - Volatile time and random functions: expressions that call
$now(),$millis()or$random()are evaluated for every row instead of once per query. - Performance: parsed expressions are cached per thread for expression columns as well as constants, and jsonata-cpp no longer throws and catches two internal exceptions for every result, which halves the per-row cost of simple expressions.
- jsonata-cpp 0.3.0.
Reference
Extension Contents
Quick reference to all available functions and settings organized by category.
| Name | Type | Description |
|---|---|---|
|
Configuration
|
||
| jsonata_max_depth | Object type: Setting | Maximum evaluation depth of a jsonata() expression, which bounds recursion in user-defined functions. |
| jsonata_timeout_ms | Object type: Setting | Maximum wall-clock time in milliseconds of a single jsonata() evaluation (one row). |
|
Functions
|
||
| jsonata() | Object type: Scalar function |
Evaluates a JSONata expression against a JSON document and returns the result as JSON.
|
| jsonata_validate() | Object type: Scalar function | Checks whether a string is a syntactically valid JSONata expression, without evaluating it. |
No extension contents match that search.
API Reference
Function Reference
Configuration
Settings
Configure the jsonata extension behavior using these settings.
jsonata_max_depth
Maximum evaluation depth of a jsonata() expression, which bounds recursion in user-defined functions. 0 removes the depth limit (a native stack guard still applies).
1000
jsonata_timeout_ms
Maximum wall-clock time in milliseconds of a single jsonata() evaluation (one row). 0 disables the timeout.
10000
Practical Examples
Cookbook
Real-world recipes and patterns for common use cases.
Extract a nested field
The simplest form — a dotted path expression replaces a chain of json_extract calls:
SELECT jsonata('Account.Name', '{"Account":{"Name":"Firefly"}}');-- "Firefly"SELECT jsonata('Order.Product.Description.Colour', payload)FROM orders;See jsonata for the function signature.
Concatenate or compute on the way out
JSONata’s & operator concatenates strings; arithmetic operators work on numbers:
SELECT jsonata('FirstName & " " & Surname', '{"FirstName":"Fred","Surname":"Smith"}');-- "Fred Smith"SELECT jsonata('Quantity * UnitPrice', '{"Quantity":3,"UnitPrice":12.50}');-- 37.5Filter an array with a predicate
The predicate-filter syntax is JSONata’s headline feature — select matching array elements, then project, in one expression:
SELECT jsonata('Phone[type="mobile"].number', payload) AS mobileFROM contacts;SELECT jsonata('items[status="open" and amount > 100].id', payload)FROM invoices;In native DuckDB JSON, the equivalent typically needs unnest plus a subquery.
Reshape into a new object
Object construction builds a fresh JSON object literal — pick fields, rename them, compute new ones — inline:
SELECT jsonata('{ "name": FirstName & " " & Surname, "mobile": Phone[type="mobile"].number, "tier": Account.Tier}', payload) AS reshapedFROM contacts;The result is a JSON object with exactly the fields you wanted — useful for building API response shapes or normalizing third-party payloads before storage.
Aggregate inside a JSON document
Use JSONata aggregation functions to roll up arrays-in-JSON without leaving the expression:
SELECT order_id, jsonata('$sum(Order.Product.(Price * Quantity))', payload)::DOUBLE AS total, jsonata('$count(Order.Product)', payload)::INTEGER AS line_itemsFROM orders;Map, filter, reduce arrays
Higher-order functions let you transform arrays element-wise:
-- Square every priceSELECT jsonata('$map(prices, function($v) { $v * $v })', '{"prices":[1,2,3,4]}');-- Keep only the high-value rowsSELECT jsonata('$filter(items, function($v) { $v.amount > 100 })', payload)FROM invoices;Parameterize an expression at query time
The 3-arg jsonata(expr, json, bindings) form supplies external $variables:
SET VARIABLE threshold = 100;
SELECT jsonata( 'items[price > $threshold].{ "id": id, "price": price }', payload, json_object('threshold', getvariable('threshold'))) AS expensive_itemsFROM line_items;The expression stays a static string (so it parses once); the per-query value rides in via bindings.
Unnest a JSONata array result into rows
When a JSONata expression returns an array, combine it with DuckDB’s unnest:
SELECT contact_id, phoneFROM ( SELECT contact_id, unnest(jsonata('Phone.number', payload)::JSON[]) AS phone FROM contacts);Run expressions stored in a table
Rules kept as data — one JSONata expression per row — work with an expression column. Use jsonata_validate (DuckDB 2.0 build) to skip rules that don’t parse instead of failing the whole query:
SELECT rule, jsonata(expr, payload) AS resultFROM (VALUES ('full name', 'FirstName & " " & Surname'), ('mobile', 'Phone[type="mobile"].number'), ('broken', 'Orders.(')) AS rules(rule, expr)CROSS JOIN contactsWHERE contact_id = 1 AND jsonata_validate(expr);Each worker thread caches its most recently used parsed expressions, so a few dozen distinct rules are parsed once each, not once per row.
Iterate before pasting
For anything more than a one-line path, prototype in the official JSONata exerciser — paste your sample document, iterate on the expression with live results, then bring it into SQL once it’s right. Same evaluator semantics as the extension.
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.53 MB |
| Linux | aarch64 | 3.83 MB |
| macOS | Apple Silicon | 3.24 MB |
| Windows | x86_64 | 10.60 MB |
| Windows | x86_64 (MinGW) | 18.34 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 JSONata: how it works, what changed, and why.
-
JSONata for DuckDB 2.0: expressions that can be stopped
JSONata for DuckDB 2.0 adds evaluation timeouts, depth limits, syntax validation, and compiled-expression caching, with RE2 patterns and correct per-row randomness.
-
Tutorial · 7 min ·
Reshape API Responses with JSONata in DuckDB
Transform supplied nested JSON payloads into consistent output documents with JSONata. Handle empty and single-item arrays and run every example in your browser.