# to\_json

[Read this page in HTML](https://www.scopedb.io/docs/reference/functions/semi-structured-data/to_json)

Serializes a semi-structured value as JSON text.

## Syntax

```scopeql
to_json(<expr>)
```

## Arguments

| Argument | Type                        | Description                                       |
| -------- | --------------------------- | ------------------------------------------------- |
| `<expr>` | `array`, `object`, or `any` | Value 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.

```scopeql
VALUES ('checkout', 3)
SELECT $0 AS service, $1 AS failures
SELECT to_json({'service': service, 'failures': failures}) AS json
```

```text
+-------------------------------------+
| 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`.

```scopeql
SELECT
    to_json({'order_id': 'o-17', 'campaign': NULL}) AS json,
    to_json(NULL::any) AS missing_payload
```

```text
+-------------------------------------+-----------------+
| json                                | missing_payload |
+-------------------------------------+-----------------+
| {"campaign":null,"order_id":"o-17"} | null            |
+-------------------------------------+-----------------+
```

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