The json_scalar() function in PostgreSQL 17 provides a straightforward way to convert SQL scalar values into their JSON equivalents. This function is particularly useful when you need to ensure proper type conversion and formatting of individual values for JSON output.
Use json_scalar() when you need to:
Convert SQL numbers to JSON numbers
Format timestamps as JSON strings
Convert SQL booleans to JSON booleans
Ensure proper null handling in JSON context
Function signature
The json_scalar() function uses the following syntax:
Parameters:
expression: Any SQL scalar value to be converted to a JSON scalar value
Example usage
Let's explore various ways to use the json_scalar() function with different types of input values.
Numeric values
String values
Date and timestamp values
Boolean values
NULL handling
Common use cases
Building JSON objects
Data type conversion
Type conversion rules
The function follows these conversion rules:
NULL -> SQL NULL
Numbers → JSON numbers (preserving exact value)
Booleans → JSON booleans
All other types → JSON strings with appropriate formatting:
Timestamps include timezone when available
Text is properly escaped according to JSON standards