Postgres array_to_json() function
Converts an SQL array to a JSON array
You can use the array_to_json
function to convert a Postgres array into its JSON
representation, transforming an array of values into a JSON
array. This helps facilitate integration with web services, APIs, and web frameworks that heavily rely on JSON
.
Function signature
Line feeds will be added between dimension 1 elements if pretty_bool
is true.
array_to_json
example
Let's consider a scenario where an e-commerce platform stores customer preferences as an array of string values in a customers
table.
customers
You can use the array_to_json
function as shown to transform the array of string values into a JSON
array:
This query returns the following result:
Advanced examples
Let's now take a look at a few advanced examples.
array_to_json
with array_agg
Use Imagine you have an e-commerce website with user's shopping cart items, as shown in the following cart_items
table:
cart_items
You can utilize array_to_json
to create a clean and efficient JSON
representation of the cart contents for a specific user.
In the example below, the row_to_json
function converts each row of the result set into a JSON
object.
The array_agg
function is an aggregate function that aggregates multiple values into an array. It is used here to aggregate the JSON
objects created by row_to_json
into a JSON
array.
This query returns the following result:
And this is the resulting JSON
structure:
NULL
in array_to_json
Handling The array_to_json
function handles NULL
values gracefully, representing them as JSON
null
within the resulting array.
Let's consider a survey_responses
table representing a survey where each participant can provide multiple responses to different questions. Some participants may not answer all questions, leading to NULL
values in the data.
The output correctly represents NULL
values as JSON
null
in the responses_json
array.
This query returns the following result:
Additional considerations
This section outlines additional considerations when using the array_to_json
function.
JSON functions
In scenarios where more control over the JSON
structure is required, consider using the json_build_array
and json_build_object
functions. These functions allow for a more fine-grained construction of JSON
objects and arrays.
array_to_json
output with pretty_bool
Formatting The pretty_bool
parameter, when set to true
, instructs array_to_json
to format the output with indentation and line breaks for improved readability.
Execute the earlier query with pretty_bool
as true
:
This query returns the following result:
note
The output displayed in psql
might be truncated or wrap long lines for visual clarity.