PostgreSQL array_to_json() Function
The PostgreSQL array_to_json()
function converts an SQL array to a JSON array and returns the JSON array.
array_to_json()
Syntax
The syntax of the PostgreSQL array_to_json()
function comes in two forms:
array_to_json(any_array ARRAY) -> JSON
or
array_to_json(any_array ARRAY, pretty BOOLEAN) -> JSON
Parameters
any_array
-
Required. SQL array to convert to JSON array.
pretty
-
Required. Whether to add newlines between top-level elements to prettify the output JSON value.
Return value
The PostgreSQL array_to_json()
function returns a JSON array converted from a specified SQL array.
If the parameter pretty
is true
, the array_to_json()
function will prettify the JSON by adding newlines between the top elements of the output JSON array.
array_to_json()
Examples
This example shows how to use the PostgreSQL array_to_json()
function to convert an SQL array to a JSON array.
SELECT array_to_json('{1, 2, 3, 4}'::int[]);
array_to_json
---------------
[1,2,3,4]
You can provide true
for parameter pretty
to prettify the JSON array as following:
SELECT array_to_json('{1, 2, 3, 4}'::int[], true);
array_to_json
---------------
[1, +
2, +
3, +
4]
You can also convert a multidimensional SQL array to a JSON array. The following example uses the array_to_json()
function to convert a two-dimensional SQL array to a JSON array.
SELECT array_to_json('{{1, 2}, {3, 4}}'::int[]);
array_to_json
---------------
[[1,2],[3,4]]