to_json

Serializes a semi-structured value as JSON text.

Syntax

to_json(<expr>)

Arguments

ArgumentTypeDescription
<expr>array, object, or anyValue to serialize. Cast a scalar to any first.

Returns

Returns string. A NULL input returns the string 'null', not a NULL result.

Examples

Serialize a result object for export

Convert a query-built object into JSON text that an application can consume.

VALUES ('checkout', 3)
SELECT $0 AS service, $1 AS failures
SELECT to_json({'service': service, 'failures': failures}) AS json
+-------------------------------------+
| json                                |
+-------------------------------------+
| {"failures":3,"service":"checkout"} |
+-------------------------------------+

The result is a string, even though its contents look like an object.

Preserve missing values in JSON

An optional campaign can be missing from an event summary. JSON serialization represents it as JSON null.

SELECT
    to_json({'order_id': 'o-17', 'campaign': NULL}) AS json,
    to_json(NULL::any) AS missing_payload
+-------------------------------------+-----------------+
| json                                | missing_payload |
+-------------------------------------+-----------------+
| {"campaign":null,"order_id":"o-17"} | null            |
+-------------------------------------+-----------------+

missing_payload is the string null, not a SQL NULL result.