Builds a JSON object out of a variadic argument list
json_build_object is used to construct a JSON object from a set of key-value pairs, creating a JSON representation of a row or set of rows. This has potential performance benefits compared to converting query results to JSON on the application side.
Function signature
json_build_object example
Let's consider a scenario where we have a table storing information about users:
users
Create the users table and insert some data into it:
Use json_build_object to create a JSON structure with user information:
This query returns the following results:
Advanced examples
Nested objects with json_build_object
Let’s say we have a table of products with an attributes column containing JSON data:
products
Create the products table and insert some data into it:
Use json_build_object to build a nested JSON object that represents the details of individual products:
This query returns the following results:
Order json_build_object output
Combine json_build_object with ORDER BY to sort the results based on a specific attribute within the JSON structure.
For example, you can build a JSON structure with json_build_object from the contents of the above products table, and then order the results based on rating.
ORDER BY was to order the results based on the descending order of rating.
This query returns the following results:
Grouped json_build_object output
To create a JSON object that groups the total price for each category of products in the products table:
This query returns the following results:
Additional considerations
Performance and indexing
The performance of the json_build_object depends on various factors including the number of key-value pairs, nested levels (deeply nested objects can be more expensive to build). Consider using JSONB data type with jsonb_build_object for better performance.
If your JSON objects have nested structures, indexing on specific paths within the nested data can be beneficial for targeted queries.
Alternative functions
Depending on your requirements, you might want to consider similar functions:
json_object - Builds a JSON object out of a text array.
json_agg - Aggregates values, as a JSON array.
row_to_json - Returns a row as a JSON object.
json_object_agg - Aggregates key-value pairs into a JSON object.