JSON_ARRAY

Description

The JSON_ARRAY constructor function builds a JSON array from a list of argument values and returns it as JSON text. This is the SQL-standard way (SQL:2016) to assemble a JSON array inline, and is commonly used to migrate queries from other systems such as Oracle, DB2, and MySQL. JSON_ARRAY is an expression that can appear anywhere a value is allowed.

Each argument is serialized with the same JSON writer as the built-in to_json function, so numbers, decimals, booleans, dates, timestamps, and nested structs/arrays/maps render the same way. Null-field handling inside a struct argument therefore follows spark.sql.jsonGenerator.ignoreNullFields, exactly as to_json does; the ON NULL clause below controls only the top-level array elements.

Syntax

JSON_ARRAY ( [ value [ FORMAT JSON ] [, ...] ]
             [ { NULL | ABSENT } ON NULL ]
             [ RETURNING data_type ] )

Parameters

Examples

-- Construct an array from a mixed value list
SELECT json_array(1, 'x', true);
+---------------------------+
|json_array(1, x, true)     |
+---------------------------+
|[1,"x",true]               |
+---------------------------+

-- ABSENT ON NULL (the default) drops NULL elements
SELECT json_array(1, NULL, 3);
+------------------------+
|json_array(1, NULL, 3)  |
+------------------------+
|[1,3]                   |
+------------------------+

-- NULL ON NULL keeps them as JSON null
SELECT json_array(1, NULL, 3 NULL ON NULL);
+--------------------------------------+
|json_array(1, NULL, 3 NULL ON NULL)   |
+--------------------------------------+
|[1,null,3]                            |
+--------------------------------------+

-- A nested JSON_ARRAY is spliced in raw (implicit FORMAT JSON)
SELECT json_array(json_array(1, 2), 3);
+---------------------------------+
|json_array(json_array(1, 2), 3)  |
+---------------------------------+
|[[1,2],3]                        |
+---------------------------------+

-- FORMAT JSON splices an already-JSON string verbatim
SELECT json_array('[1,2]' FORMAT JSON);
+----------------------------------+
|json_array([1,2] FORMAT JSON)     |
+----------------------------------+
|[[1,2]]                           |
+----------------------------------+