|
| 1 | +--- |
| 2 | +title: JSON_OBJECT_AGG |
| 3 | +--- |
| 4 | + |
| 5 | +import FunctionDescription from '@site/src/components/FunctionDescription'; |
| 6 | + |
| 7 | +<FunctionDescription description="Introduced or updated: v1.2.611"/> |
| 8 | + |
| 9 | +Converts key-value pairs into a JSON object. For each row in the input, it generates a key-value pair where the key is derived from the `<key_expression>` and the value is derived from the `<value_expression>`. These key-value pairs are then combined into a single JSON object. |
| 10 | + |
| 11 | +See also: [JSON_ARRAY_AGG](aggregate-json-array-agg.md) |
| 12 | + |
| 13 | +## Syntax |
| 14 | + |
| 15 | +```sql |
| 16 | +JSON_OBJECT_AGG(<key_expression>, <value_expression>) |
| 17 | +``` |
| 18 | + |
| 19 | +| Parameter | Description | |
| 20 | +|------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------| |
| 21 | +| key_expression | Specifies the key in the JSON object. **Only supports string** expressions. If the `key_expression` evaluates to NULL, the key-value pair is skipped. | |
| 22 | +| value_expression | Specifies the value in the JSON object. It can be any supported data type. If the `value_expression` evaluates to NULL, the key-value pair is skipped. | |
| 23 | + |
| 24 | +## Return Type |
| 25 | + |
| 26 | +JSON object. |
| 27 | + |
| 28 | +## Examples |
| 29 | + |
| 30 | +This example demonstrates how JSON_OBJECT_AGG can be used to aggregate different types of data—such as decimals, integers, JSON variants, and arrays—into JSON objects, with the column b as the key for each JSON object: |
| 31 | + |
| 32 | +```sql |
| 33 | +CREATE TABLE d ( |
| 34 | + a DECIMAL(10, 2), |
| 35 | + b STRING, |
| 36 | + c INT, |
| 37 | + d VARIANT, |
| 38 | + e ARRAY(STRING) |
| 39 | +); |
| 40 | + |
| 41 | +INSERT INTO d VALUES |
| 42 | + (20, 'abc', NULL, '{"k":"v"}', ['a','b']), |
| 43 | + (10, 'de', 100, 'null', []), |
| 44 | + (4.23, NULL, 200, '"uvw"', ['x','y']), |
| 45 | + (5.99, 'xyz', 300, '[1,2,3]', ['z']); |
| 46 | + |
| 47 | +SELECT |
| 48 | + json_object_agg(b, a) AS json_a, |
| 49 | + json_object_agg(b, c) AS json_c, |
| 50 | + json_object_agg(b, d) AS json_d, |
| 51 | + json_object_agg(b, e) AS json_e |
| 52 | +FROM |
| 53 | + d; |
| 54 | + |
| 55 | +-[ RECORD 1 ]----------------------------------- |
| 56 | +json_a: {"abc":20.0,"de":10.0,"xyz":5.99} |
| 57 | +json_c: {"de":100,"xyz":300} |
| 58 | +json_d: {"abc":{"k":"v"},"de":null,"xyz":[1,2,3]} |
| 59 | +json_e: {"abc":["a","b"],"de":[],"xyz":["z"]} |
| 60 | +``` |
0 commit comments