

# JSON creation functions

Use these functions to build JSON arrays and objects from values, and to convert SQL values, such as lists, structs, and whole rows, to JSON.

The aggregate functions build one JSON array or object from the rows of each group.

## `json_array` function
<a name="athena-duckdb-functions-json-json-array"></a>

Returns a JSON array that holds each argument, in order. Each argument is converted to JSON: numbers and Boolean values stay as they are, strings become JSON strings, lists become arrays, structs become objects, and dates and timestamps become strings. A `NULL` argument becomes the JSON value `null`. With no arguments, the result is an empty array, `[]`.

A `VARCHAR` argument becomes a JSON string even when it holds JSON text. To put JSON text into the array as an object or array, cast it to `JSON` first.

### Syntax
<a name="athena-duckdb-functions-json-json-array-syntax"></a>

```sql
json_array([ {{value}} [, ...] ])
```

### Arguments
<a name="athena-duckdb-functions-json-json-array-arguments"></a>

The `json_array` function takes the following argument:

**{{value}}**  
A value to put in the array, of any type. You can pass any number of values. This argument is optional.

### Return type
<a name="athena-duckdb-functions-json-json-array-return-type"></a>

`JSON`

### Examples
<a name="athena-duckdb-functions-json-json-array-examples"></a>

The following SQL query builds an array from a number, a string, a Boolean value, and a `NULL`.

```sql
SELECT json_array(1, 'x', true, NULL) AS result
```

The query returns the following result.


| result | 
| --- | 
| `[1,"x",true,null]` | 

The following SQL query calls `json_array` with no arguments, which returns an empty array.

```sql
SELECT json_array() AS result
```

The query returns the following result.


| result | 
| --- | 
| `[]` | 

The following SQL query passes the same JSON text twice. As a `VARCHAR` value, it becomes a JSON string. After a cast to `JSON`, it becomes an object in the array.

```sql
SELECT
    json_array('{"a": 1}') AS as_string,
    json_array('{"a": 1}'::JSON) AS as_object
```

The query returns the following result.


| as\_string | as\_object | 
| --- | --- | 
| `["{\"a\": 1}"]` | `[{"a":1}]` | 

The following SQL query shows that a `DECIMAL(10,2)` value loses its trailing zero, and that a `DECIMAL(16,2)` value keeps it.

```sql
SELECT
    json_array(
        CAST(1.50 AS DECIMAL(10, 2)),
        CAST(1.50 AS DECIMAL(16, 2))
    ) AS result
```

The query returns the following result.


| result | 
| --- | 
| `[1.5,1.50]` | 

### Considerations
<a name="athena-duckdb-functions-json-json-array-considerations"></a>

`json_array` writes a `DECIMAL` value with a precision of 15 digits or fewer as a `DOUBLE`, so the value loses its trailing zeros, and `CAST(1.50 AS DECIMAL(10,2))` becomes `1.5`. To keep the zeros, first cast the value to a precision of 16 or more with the same scale, as in `CAST({{value}} AS DECIMAL(16,2))`.

### Differences from Athena engine version 3
<a name="athena-duckdb-functions-json-json-array-differences-from-engine-version-3"></a>

Athena engine version 3 keeps the trailing zeros of a `DECIMAL` value when it converts the value to JSON. In contrast, DuckDB writes a `DECIMAL` value with a precision of 15 digits or fewer as a `DOUBLE`, so `json_array(CAST(1.50 AS DECIMAL(10,2)))` returns `[1.5]`. To keep the zeros, cast the value to `DECIMAL(16,2)` or wider first.

## `json_group_array` function
<a name="athena-duckdb-functions-json-json-group-array"></a>

Returns a JSON array with one element for each row in the group. Each value is converted to JSON in the same way as `to_json`: a string becomes a JSON string, a list becomes an array, and a struct becomes an object. A `NULL` value becomes the JSON `null`, so the array always has as many elements as the group has rows.

If the group has no rows, the result is `NULL`, not an empty array. To get an empty array instead, use `coalesce(json_group_array({{expression}}), CAST('[]' AS JSON))`.

### Syntax
<a name="athena-duckdb-functions-json-json-group-array-syntax"></a>

```sql
json_group_array({{expression}})
```

### Arguments
<a name="athena-duckdb-functions-json-json-group-array-arguments"></a>

The `json_group_array` function takes the following argument:

**{{expression}}**  
The values to collect. You can pass any type. The function adds a `VARCHAR` value as a JSON string even if it holds JSON text, so cast such a value to `JSON` to add it as nested JSON.

### Return type
<a name="athena-duckdb-functions-json-json-group-array-return-type"></a>

`JSON`

### Examples
<a name="athena-duckdb-functions-json-json-group-array-examples"></a>

The following SQL query collects three values into a JSON array. The `NULL` value becomes the JSON `null`.

```sql
SELECT
    json_group_array(x) AS result FROM (VALUES
        (1),
        (2),
        (NULL)
    ) AS v(x)
```

The query returns the following result.


| result | 
| --- | 
| `[1,2,null]` | 

The following SQL query builds one JSON array for each category. Each category has one item, so each array has one element. When a group has more than one row, the order of the elements is not guaranteed.

```sql
SELECT
    category,
    json_group_array(item) AS items FROM (VALUES
        ('fruit', 'apple'),
        ('vegetable', 'kale')
    ) AS v(category, item)
GROUP BY category ORDER BY category
```

The query returns the following results.


| category | items | 
| --- | --- | 
| `fruit` | `["apple"]` | 
| `vegetable` | `["kale"]` | 

The following SQL query uses a `WHERE` clause that filters out every row, so `json_group_array` has no rows to aggregate and returns `NULL`. The `coalesce` function replaces the `NULL` with an empty JSON array.

```sql
SELECT
    json_group_array(x) IS NULL AS is_null,
    coalesce(
        json_group_array(x), CAST('[]' AS JSON)
    ) AS with_default
FROM (VALUES (1), (2)) AS v(x) WHERE x > 5
```

The query returns the following result.


| is\_null | with\_default | 
| --- | --- | 
| `true` | `[]` | 

The following SQL query builds a sorted JSON array with `to_json` and `list`, because `json_group_array` does not accept `ORDER BY`. The `NULL` value sorts last.

```sql
SELECT
    to_json(
        list(x ORDER BY x)
    ) AS result
FROM (VALUES (3), (1), (NULL), (2)) AS v(x)
```

The query returns the following result.


| result | 
| --- | 
| `[1,2,3,null]` | 

### Considerations
<a name="athena-duckdb-functions-json-json-group-array-considerations"></a>

`json_group_array` is a macro, not a built-in aggregate function, so a call with `DISTINCT`, `ORDER BY`, or `FILTER` fails. To sort the elements or remove duplicates, use the [`to_json` function](#athena-duckdb-functions-json-to-json) with `list` instead, for example `to_json(list(DISTINCT {{expression}} ORDER BY {{expression}}))`. To leave rows out, use a `WHERE` clause.

The elements follow the order in which rows reach the function, which is not guaranteed. When the order matters, use `to_json(list({{expression}} ORDER BY {{sort_expression}}))`.

A `DECIMAL` value with a width of 15 digits or less is written without trailing zeros, so `1.50` becomes `1.5`. To keep the zeros, cast the value to a `DECIMAL` with a width of 16 or more and the same scale before you aggregate it.

## `json_group_object` function
<a name="athena-duckdb-functions-json-json-group-object"></a>

Returns a JSON object with one member for each row in the group. The function converts each `key` to `VARCHAR`, so a number key such as `1` becomes the string `"1"`. It converts each `value` to JSON in the same way as `to_json`, and a `NULL` value becomes the JSON `null`.

If the group has no rows, the result is `NULL`, not an empty object.

### Syntax
<a name="athena-duckdb-functions-json-json-group-object-syntax"></a>

```sql
json_group_object({{key}}, {{value}})
```

### Arguments
<a name="athena-duckdb-functions-json-json-group-object-arguments"></a>

The `json_group_object` function takes the following arguments:

**{{key}}**  
The member names. Any type is allowed, and the value is converted to `VARCHAR`. A key must not be `NULL`.

**{{value}}**  
The member values. You can pass any type. The function adds a `VARCHAR` value as a JSON string even if it holds JSON text, so cast such a value to `JSON` to add it as nested JSON.

### Return type
<a name="athena-duckdb-functions-json-json-group-object-return-type"></a>

`JSON`

### Examples
<a name="athena-duckdb-functions-json-json-group-object-examples"></a>

The following SQL query builds a JSON object from two rows. The `NULL` value becomes the JSON `null`.

```sql
SELECT
    json_group_object(
        key_name, amount
    ) AS result
FROM (
    VALUES ('a', 1), ('b', NULL)
) AS v(key_name, amount)
```

The query returns the following result.


| result | 
| --- | 
| `{"a":1,"b":null}` | 

The following SQL query uses `INTEGER` keys. The keys become JSON strings.

```sql
SELECT
    json_group_object(
        id, customer
    ) AS result
FROM (
    VALUES (1, 'alice'), (2, 'bob')
) AS v(id, customer)
```

The query returns the following result.


| result | 
| --- | 
| `{"1":"alice","2":"bob"}` | 

The following SQL query has two rows with the key `a`. The object keeps both members, so `json_keys` lists the key twice. The order of the members is not guaranteed, so the query shows the keys instead of the object.

```sql
SELECT
    json_keys(
        json_group_object(key_name, amount)
    ) AS member_keys
FROM (VALUES ('a', 1), ('a', 2)) AS v(key_name, amount)
```

The query returns the following result.


| member\_keys | 
| --- | 
| `[a, a]` | 

The following SQL query leaves out the row whose key is `NULL`. Without the `WHERE` clause, the query fails.

```sql
SELECT
    json_group_object(
        key_name, amount
    ) AS result
FROM (VALUES ('a', 1), (NULL, 2)) AS v(key_name, amount)
WHERE key_name IS NOT NULL
```

The query returns the following result.


| result | 
| --- | 
| `{"a":1}` | 

### Considerations
<a name="athena-duckdb-functions-json-json-group-object-considerations"></a>

If any `key` in the group is `NULL`, the query fails. Leave those rows out first, for example with `WHERE {{key}} IS NOT NULL`.

The function does not remove duplicate keys. When two rows have the same key, the object holds that key twice, and functions such as `json_extract_string` read the first one.

`json_group_object` is a macro, not a built-in aggregate function, so a call with `DISTINCT`, `ORDER BY`, or `FILTER` fails. The members follow the order in which rows reach the function, which is not guaranteed.

## `json_object` function
<a name="athena-duckdb-functions-json-json-object"></a>

Returns a JSON object built from alternating `key` and `value` arguments. The members keep the order of the arguments, and duplicate keys are kept. Each value is converted to JSON in the same way as `to_json` converts it. A string becomes a JSON string, a list becomes an array, a struct becomes an object, and a date or timestamp becomes a JSON string. A `NULL` value becomes the JSON `null`.

With no arguments, the function returns the empty object `{}`.

### Syntax
<a name="athena-duckdb-functions-json-json-object-syntax"></a>

```sql
json_object([ {{key}}, {{value}} [, ...] ])
```

### Arguments
<a name="athena-duckdb-functions-json-json-object-arguments"></a>

The `json_object` function takes the following arguments:

**{{key}}**  
A member name, as a `VARCHAR`. A key of another type fails the query, so cast such a key with `CAST({{key}} AS VARCHAR)`. A `NULL` key fails the query even after the cast.

**{{value}}**  
The member value. You can pass any type. The function adds a `VARCHAR` value as a JSON string even if it holds JSON text, so cast such a value to `JSON` to add it as nested JSON.

### Return type
<a name="athena-duckdb-functions-json-json-object-return-type"></a>

`JSON`

### Examples
<a name="athena-duckdb-functions-json-json-object-examples"></a>

The following SQL query builds an object with a number and a string member.

```sql
SELECT
    json_object('duck', 42, 'name', 'mallard') AS result
```

The query returns the following result.


| result | 
| --- | 
| `{"duck":42,"name":"mallard"}` | 

The following SQL query adds a list, a struct, a `JSON` value, and a `VARCHAR` value that holds JSON text. Only the `JSON` value is nested; the `VARCHAR` value becomes a JSON string.

```sql
SELECT
    json_object(
        'tags', ['a', 'b'], 'point', {'x': 1, 'y': 2},
        'doc', CAST('{"v": 1}' AS JSON), 'text',
        '{"v": 1}'
    ) AS result
```

The query returns the following result.


| result | 
| --- | 
| `{"tags":["a","b"],"point":{"x":1,"y":2},"doc":{"v":1},"text":"{\"v\": 1}"}` | 

The following SQL query builds an empty object, and an object whose value is `NULL`.

```sql
SELECT
    json_object() AS empty_object,
    json_object('a', NULL) AS null_value
```

The query returns the following result.


| empty\_object | null\_value | 
| --- | --- | 
| `{}` | `{"a":null}` | 

The following SQL query adds the same `DECIMAL` value twice. The value with a width of 10 digits loses its trailing zero, and the value with a width of 16 digits keeps it.

```sql
SELECT
    json_object(
        'narrow', CAST(1.50 AS DECIMAL(10,2)), 'wide',
        CAST(1.50 AS DECIMAL(16,2))
    ) AS result
```

The query returns the following result.


| result | 
| --- | 
| `{"narrow":1.5,"wide":1.50}` | 

### Considerations
<a name="athena-duckdb-functions-json-json-object-considerations"></a>

The function needs an even number of arguments. A call with an odd number of arguments fails.

### Differences from Athena engine version 3
<a name="athena-duckdb-functions-json-json-object-differences-from-engine-version-3"></a>

Athena engine version 3 uses the SQL standard syntax for `json_object`, with `VALUE` between each key and its value, for example `json_object('a' VALUE 1, 'b' VALUE 'x')`. In DuckDB, pass the keys and values as alternating arguments instead, for example `json_object('a', 1, 'b', 'x')`.

In DuckDB, a `DECIMAL` value with a width of 15 digits or less is written to JSON as a `DOUBLE`, so trailing zeros are lost and `1.50` becomes `1.5`. By contrast, Athena engine version 3 keeps the zeros. To keep them, cast the value to a `DECIMAL` with a width of 16 or more and the same scale, for example `CAST({{value}} AS DECIMAL(16,2))`.

## `row_to_json` function
<a name="athena-duckdb-functions-json-row-to-json"></a>

Returns `struct` as a JSON object with one member for each field, in field order. Field values are converted in the same way as `to_json` converts them, and a field that is `NULL` becomes a member whose value is JSON `null`. If `struct` is `NULL`, the result is `NULL`.

To convert each row of a query to JSON, pass the table alias, as in `row_to_json(t)`. To convert a value of another type, use the [`to_json` function](#athena-duckdb-functions-json-to-json).

### Syntax
<a name="athena-duckdb-functions-json-row-to-json-syntax"></a>

```sql
row_to_json({{struct}})
```

### Arguments
<a name="athena-duckdb-functions-json-row-to-json-arguments"></a>

The `row_to_json` function takes the following argument:

**{{struct}}**  
The struct to convert, as a `STRUCT` value with named fields, such as `{'id': 1, 'name': 'alice'}`, or a table alias, which stands for the whole row as a `STRUCT`.

### Return type
<a name="athena-duckdb-functions-json-row-to-json-return-type"></a>

`JSON`

### Examples
<a name="athena-duckdb-functions-json-row-to-json-examples"></a>

The following SQL query converts a struct with one field to a JSON object.

```sql
SELECT row_to_json({'a': 1}) AS result
```

The query returns the following result.


| result | 
| --- | 
| `{"a":1}` | 

The following SQL query converts a struct that has a list field and a field that is `NULL`.

```sql
SELECT
    row_to_json(
        {
            'id': 1, 'name': 'alice',
            'tags': ['x', 'y'], 'note': NULL
        }
    ) AS result
```

The query returns the following result.


| result | 
| --- | 
| `{"id":1,"name":"alice","tags":["x","y"],"note":null}` | 

The following SQL query passes the table alias `v` to convert each row to a JSON object.

```sql
SELECT row_to_json(v) AS result
FROM (VALUES (1, 'alice'), (2, 'bob')) AS v(id, name)
ORDER BY id
```

The query returns the following results.


| result | 
| --- | 
| `{"id":1,"name":"alice"}` | 
| `{"id":2,"name":"bob"}` | 

### Considerations
<a name="athena-duckdb-functions-json-row-to-json-considerations"></a>

The argument must be a `STRUCT` with named fields. A value of another type, or the struct without field names that `ROW(1, 'a')` creates, makes the query fail. Name the fields with a struct literal, as in `{'id': 1, 'name': 'a'}`.

The function takes exactly one argument.

## `to_json` function
<a name="athena-duckdb-functions-json-to-json"></a>

Returns `value` converted to JSON. A string becomes a JSON string in double quotes, and a number or a boolean becomes a JSON number or boolean. A list becomes a JSON array, and a `STRUCT` or `MAP` becomes a JSON object. Dates, timestamps, and values of other types become JSON strings. A `NULL` inside a list, struct, or map becomes JSON `null`. If `value` is `NULL`, the result is `NULL`.

`to_json` does not parse a string as JSON text, so `to_json('[1,2]')` returns the JSON string `"[1,2]"`. To parse JSON text, use `CAST({{string}} AS JSON)` or the `json` function. To convert a whole row, pass the table alias, or use `row_to_json`.

`json_quote` is an alias of `to_json`.

### Syntax
<a name="athena-duckdb-functions-json-to-json-syntax"></a>

```sql
to_json({{value}})
```

### Arguments
<a name="athena-duckdb-functions-json-to-json-arguments"></a>

The `to_json` function takes the following argument:

**{{value}}**  
The value to convert. It can be of any type.

### Return type
<a name="athena-duckdb-functions-json-to-json-return-type"></a>

`JSON`

### Examples
<a name="athena-duckdb-functions-json-to-json-examples"></a>

The following SQL query converts a struct to a JSON object.

```sql
SELECT to_json({'a': 1}) AS result
```

The query returns the following result.


| result | 
| --- | 
| `{"a":1}` | 

The following SQL query converts a string, a number, and a list that has a `NULL` element.

```sql
SELECT
    to_json('abc') AS text_value,
    to_json(42) AS number_value,
    to_json([1, 2, NULL]) AS list_value
```

The query returns the following result.


| text\_value | number\_value | list\_value | 
| --- | --- | --- | 
| `"abc"` | `42` | `[1,2,null]` | 

The following SQL query compares `to_json` with a cast to `JSON` for the same text. `to_json` returns a JSON string, and the cast parses the text as an array.

```sql
SELECT
    to_json('[1,2]') AS as_string,
    CAST('[1,2]' AS JSON) AS as_parsed
```

The query returns the following result.


| as\_string | as\_parsed | 
| --- | --- | 
| `"[1,2]"` | `[1,2]` | 

The following SQL query converts the same decimal value with two precisions. Only the value with a precision of 16 keeps its trailing zeros.

```sql
SELECT
    to_json(CAST('1.5000' AS DECIMAL(10,4))) AS narrow,
    to_json(CAST('1.5000' AS DECIMAL(16,4))) AS wide
```

The query returns the following result.


| narrow | wide | 
| --- | --- | 
| `1.5` | `1.5000` | 

### Considerations
<a name="athena-duckdb-functions-json-to-json-considerations"></a>

A `DECIMAL` value with a precision of 15 or less is written as a `DOUBLE`, so its trailing zeros are lost: `1.5000` becomes `1.5`. To keep them, cast the value to a precision of 16 or more with the same scale first, as in `to_json(CAST({{x}} AS DECIMAL(16,4)))`. This also works for values inside lists, structs, and maps.

The function takes exactly one argument.

### Differences from Athena engine version 3
<a name="athena-duckdb-functions-json-to-json-differences-from-engine-version-3"></a>

In Athena engine version 3, `CAST({{string}} AS JSON)` returns the string as a JSON string value. In DuckDB, the same cast parses the string as JSON text, so `CAST('[1,2]' AS JSON)` returns the array `[1,2]`. To get the Athena engine version 3 result, use `to_json({{string}})`.

In DuckDB, `CAST({{string}} AS JSON)` makes the query fail when the string is not JSON text, such as `'abc'`. To convert such a string to a JSON string value, as Athena engine version 3 does, use `to_json({{string}})`.

Athena engine version 3 keeps the trailing zeros of a `DECIMAL` value that it converts to JSON. In DuckDB, a `DECIMAL` with a precision of 15 or less is written as a `DOUBLE`, so `1.5000` becomes `1.5`. Cast to a precision of 16 or more with the same scale before the conversion to keep the zeros.

Some JSON text differs although the JSON value is the same. Athena engine version 3 writes very small `DECIMAL` values in E notation, such as `-1E-10`, escapes emoji, and sorts map keys. For a `DECIMAL` with a precision of 16 or more, DuckDB writes `-0.0000000001`. It also writes emoji as they are, and keeps map keys in the order in which they were added.