JSON_OBJECT

Description

The JSON_OBJECT constructor function builds a JSON object from key/value pairs and returns it as JSON text. This is the SQL-standard way (SQL:2016) to assemble a JSON object inline, with common compatibility syntax from other systems. JSON_OBJECT is an expression that can appear anywhere a value is allowed.

Each value 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 value therefore follows spark.sql.jsonGenerator.ignoreNullFields, exactly as to_json does; the ON NULL clause below controls only the top-level object members.

This is an initial subset of the SQL:2016 JSON_OBJECT constructor. It supports the key/value members, the value-level FORMAT JSON marker, the { NULL | ABSENT } ON NULL clause, and a string-type RETURNING. The following SQL/JSON clauses are not yet supported:

Syntax

JSON_OBJECT ( [ { key VALUE value | KEY key VALUE value | key : value } [ FORMAT JSON ] [, ...] ]
              [ { NULL | ABSENT } ON NULL ]
              [ RETURNING data_type ] )

JSON_OBJECT ( [ key, value [, key, value] ... ]
              [ { NULL | ABSENT } ON NULL ]
              [ RETURNING data_type ] )

Parameters

Examples

-- Construct an object from key/value pairs
SELECT json_object('id' VALUE 7, 'name' VALUE 'Ada') AS obj;
+---------------------+
|obj                  |
+---------------------+
|{"id":7,"name":"Ada"}|
+---------------------+

-- KEY before the member name is also accepted
SELECT json_object(KEY 'id' VALUE 7, KEY 'name' VALUE 'Ada') AS obj;
+---------------------+
|obj                  |
+---------------------+
|{"id":7,"name":"Ada"}|
+---------------------+

-- The `:` separator is equivalent to VALUE; NULL ON NULL (the default) keeps null members
SELECT json_object('id' : 7, 'v' : NULL) AS obj;
+-----------------+
|obj              |
+-----------------+
|{"id":7,"v":null}|
+-----------------+

-- Comma-separated key/value pairs are also accepted
SELECT json_object('id', 7, 'name', 'Ada') AS obj;
+---------------------+
|obj                  |
+---------------------+
|{"id":7,"name":"Ada"}|
+---------------------+

-- ABSENT ON NULL omits members whose value is NULL
SELECT json_object('id' : 7, 'v' : NULL ABSENT ON NULL) AS obj;
+--------+
|obj     |
+--------+
|{"id":7}|
+--------+

-- A nested JSON_OBJECT composes and is spliced in raw
SELECT json_object('a' VALUE json_object('b' VALUE 1)) AS obj;
+-------------+
|obj          |
+-------------+
|{"a":{"b":1}}|
+-------------+

-- FORMAT JSON splices an already-JSON string verbatim instead of quoting it
SELECT json_object('a' VALUE '{"b":1}' FORMAT JSON) AS obj;
+-------------+
|obj          |
+-------------+
|{"a":{"b":1}}|
+-------------+