PostgreSQL row_to_json() Function
The PostgreSQL row_to_json()
function converts a value of an SQL composite type to a JSON object and returns it.
row_to_json()
Syntax
The syntax of the PostgreSQL row_to_json()
function comes in two forms:
row_to_json(any_row RECORD) -> JSON
or
row_to_json(any_row RECORD, pretty BOOLEAN) -> JSON
Parameters
any_array
-
Required. The value of the SQL composite type to convert to a JSON object. We can use the row expression to construct a value of a composite type.
pretty
-
Required. Whether to add newlines between top-level elements to prettify the output JSON value.
Return value
The PostgreSQL row_to_json()
function returns a JSON object converted from a value of a specified SQL composite type.
If the parameter pretty
is true
, the row_to_json()
function will prettify the JSON by adding newlines between top-level elements of the output JSON object.
row_to_json()
Examples
This example shows how to use the PostgreSQL row_to_json()
function to convert a SQL composite type value to a JSON object.
SELECT row_to_json(row('Tom', 20, 'He likes sports.'));
row_to_json
----------------------------------------------
{"f1":"Tom","f2":20,"f3":"He likes sports."}
Here, we use the row
expression row('Tom', 20, 'He likes sports.')
to construct a value of a composite type. The value of this composite type contains 3 elements: 'Tom'
, 20
and 'He likes sports.'
.
When converting a composite type value into a JSON object, the row_to_json()
function automatically generates keys of the object in the format fn
, where n
is a number, increasing from 1.
You can provide true
for the parameter pretty
to beautify the output JSON object like:
SELECT row_to_json(row('Tom', 20, 'He likes sports.'), true);
row_to_json
---------------------------
{"f1":"Tom", +
"f2":20, +
"f3":"He likes sports."}