The json_serialize() function in PostgreSQL 17 provides a flexible way to convert JSON values into text or binary format. This function is particularly useful when you need to control the output format of JSON data or prepare it for transmission or storage in specific formats.
Use json_serialize() when you need to:
Convert JSON values to specific text formats
Transform JSON into binary representation
Ensure consistent JSON string formatting
Prepare JSON data for external systems or storage
Function signature
The json_serialize() function uses the following syntax:
Parameters:
expression: Input JSON value or expression to serialize
FORMAT JSON: Explicitly specifies JSON format for input (optional)
ENCODING UTF8: Specifies UTF8 encoding for input/output (optional)
RETURNING data_type: Specifies the desired output type (optional, defaults to text)
Example usage
Let's explore various ways to use the json_serialize() function with different inputs and output formats.
Basic serialization
Binary serialization
Working with complex structures
Comparison with json() function
While both json_serialize() and json() work with JSON data, they serve different purposes:
json() converts text or binary data into JSON values
json_serialize() converts JSON values into text or binary format
json() focuses on input validation (e.g., WITH UNIQUE keys)