Sub topic 6
Building JSON with `jsonb_build_object` and `jsonb_agg`
Assume you know how to query tables and read values from a jsonb column. This chapter uses the orders table from earlier examples, where customer is a SQL column and details stores order data as JSONB.
PostgreSQL can create JSON output from ordinary SQL values. Two useful functions are:
jsonb_build_objectcreates one JSON object from key-value pairs.jsonb_aggcollects multiple values into one JSON array.
These functions are useful when an application needs a nested API response instead of a flat result set.
Creating one JSON object
Pass alternating keys and values to jsonb_build_object. Keys are written as strings. Values can be columns, expressions, or other JSON values.
SELECT jsonb_build_object(
'customer', customer,
'total', (details ->> 'total')::numeric,
'status', details ->> 'status',
'city', details #>> '{shipping,city}'
) AS summary
FROM orders;For Ada, the result has this general shape:
{
"customer": "Ada",
"total": 42.50,
"status": "paid",
"city": "Oslo"
}The cast to numeric matters. Without it, details ->> 'total' is text, so the JSON value could be emitted as a JSON string rather than a number.
You can also nest one JSON object inside another:
SELECT jsonb_build_object(
'id', id,
'customer', customer,
'shipping', details -> 'shipping'
) AS order_summary
FROM orders;The -> operator keeps the shipping value as JSONB, so the nested object remains an object in the result.
Collecting rows into an array
jsonb_agg turns values from several rows into one JSON array. Combine it with jsonb_build_object to produce an array of objects.
SELECT jsonb_agg(
jsonb_build_object(
'id', id,
'customer', customer,
'status', details ->> 'status'
)
ORDER BY id
) AS orders
FROM orders;The ORDER BY belongs inside jsonb_agg. Without it, SQL does not promise the order of values in the aggregate.
If the query finds no rows, jsonb_agg returns SQL NULL, not an empty JSON array. Use COALESCE when clients require [].
SELECT COALESCE(
jsonb_agg(jsonb_build_object('id', id) ORDER BY id),
'[]'::jsonb
) AS orders
FROM orders
WHERE details ->> 'status' = 'cancelled';Building nested responses
You can aggregate JSON values inside an object. The following query returns one object for each order and includes an array of its items.
SELECT jsonb_build_object(
'id', o.id,
'customer', o.customer,
'items',
COALESCE(
(
SELECT jsonb_agg(
jsonb_build_object(
'sku', item ->> 'sku',
'qty', (item ->> 'qty')::int
)
ORDER BY item ->> 'sku'
)
FROM jsonb_array_elements(o.details -> 'items') AS item
),
'[]'::jsonb
)
) AS order_document
FROM orders AS o;jsonb_array_elements expands the stored items array into rows. The inner query converts those rows back into an array of smaller objects. The outer function places that array under the items key.
| Function | Result | Typical use |
|---|---|---|
| `jsonb_build_object` | One JSON object | Shape one response record |
| `jsonb_agg` | One JSON array | Collect records or values |
| `jsonb_array_elements` | Several SQL rows | Expand a JSON array before rebuilding it |
Common errors
- Use valid JSONB values for nested data. A quoted text value becomes a JSON string, while a JSONB expression remains an object or array.
- Cast extracted text before building numeric or Boolean JSON values.
- Add an aggregate
ORDER BYwhen array order matters. - Use
COALESCEif an empty array is required instead ofnull. - Watch for duplicate object keys. When PostgreSQL builds an object, later values for the same key replace earlier values.
Exercise
Write a query that returns one JSON array containing an object with each order's id and numeric total. What should the query return when no orders match?
Show answer
Use jsonb_agg(jsonb_build_object('id', id, 'total', (details ->> 'total')::numeric)). It returns SQL NULL when no rows match, so wrap the aggregate in COALESCE(..., '[]'::jsonb) to return an empty JSON array.