PostgreSQL – to_json Function

The to_json function in PostgreSQL is used to convert a PostgreSQL row or value into its corresponding JSON representation. This function is often used when you want to convert data from a table or a single value into JSON format.

Here are some common use cases for the to_json function:

Convert a Row to JSON:

You can use the to_json function to convert an entire row from a table into a JSON object.

SELECT to_json(users) FROM users WHERE id = 1; 

In this example, assuming there’s a table named users, the to_json function converts the row corresponding to the user with id 1 into a JSON object.

Convert a Value to JSON:

You can also use the to_json function to convert a single value into a JSON format.

SELECT to_json('Hello, World!') AS json_value; 

This query will return a result with a single column named json_value containing the JSON representation of the string 'Hello, World!'.

Convert a Query Result to JSON Array:

You can use the json_agg function in combination with the to_json function to convert the result of a query into a JSON array.

SELECT json_agg(to_json(users)) FROM users; 

This query aggregates all rows from the users table into a JSON array.

The to_json function is primarily used to convert individual values or rows to JSON format. If you need more advanced manipulation or querying of JSON data, you might want to explore other JSON functions and operators available in PostgreSQL.

Similar Posts