Applies to: ✅ Data 360 SQL ✅ Tableau Hyper API
Converts a value to its JSON representation.
Syntax
json_scalar(<value>)
Arguments
Required
<value>: The value to convert. Can be a number, Boolean, string, date/time value,jsonvalue, SQL array, or row.
Returns
Returns a json value.
- Numbers, Booleans, and
jsonvalues are represented directly. - Any other scalar uses its text representation, escaped as needed to form a valid JSON string.
- SQL arrays become JSON arrays, converted recursively.
- Rows become JSON objects.
- A
NULLinput returns SQLNULL, not the JSON literalnull. - Values already typed as
jsonare forwarded unchanged.
Considerations
- The conversion is similar to a text cast, but uses a slightly different format for dates and timestamps. Dates use the form
2022-01-01, timestamps use2022-01-01T01:02:03.005, and timestamps with time zone include the offset, for example2022-01-01T01:02:03.005+00:00. - Special floating-point values are represented as JSON strings:
"NaN","Infinity", and"-Infinity". The values0and-0are distinguished. bigintandnumericvalues are printed in full, even when they aren't exactly representable as JavaScript numbers.- Some types can't be converted, such as
bytes.
Examples
Convert Scalar Values
Numbers and Booleans are represented directly, while strings are escaped into JSON strings.
SELECT
json_scalar(-1::int) AS number,
json_scalar(true) AS boolean,
json_scalar('{"a":1}'::text) AS string;
Returns -1, true, and "{\"a\":1}".
Preserve Embedded JSON
A json-typed value is preserved as JSON rather than escaped.
SELECT json_scalar('{"a":1}'::json) AS result;
Returns {"a":1}.
Convert Date and Time Values
Date and time values use the JSON-friendly format.
SELECT
json_scalar('2022-01-01'::date) AS date_value,
json_scalar('2022-01-01 01:02:03.005'::timestamp) AS timestamp_value;
Returns "2022-01-01" and "2022-01-01T01:02:03.005".
Convert Arrays and Rows
SQL arrays become JSON arrays, and rows become JSON objects.
SELECT
json_scalar('[-1, 1]'::int[]) AS array_value,
json_scalar(ROW(42 AS a, 'text' AS b, true AS c)) AS row_value;
Returns [-1,1] and {"a":42,"b":"text","c":true}.
NULL Input
A NULL input returns SQL NULL, not the JSON literal null.
SELECT json_scalar(NULL::int) IS NULL AS is_null;
Returns true.
Related Documentation
- JSON Type
[JSON_ARRAY](./json-array.md)- Build a JSON array from a list of values.[JSON_OBJECT](./json-object.md)- Build a JSON object from key-value pairs.[json](./json-constructor.md)- Parse a string into a JSON value.