Sub topic 6
Building JSON with jsonb_build_object and jsonb_agg
Earlier chapters read and filter JSON that is already stored. This chapter goes the other way: you produce JSON from ordinary relational rows. Typical uses are API responses built inside the database, denormalized snapshots, and nested documents assembled from parent and child tables.
This chapter assumes you know SELECT, JOIN, GROUP BY and aggregate functions, and that you have met the jsonb type and the -> and ->> operators. Any PostgreSQL version from 12 onward works for every example.
Setup
The examples use two small relational tables. Customer 3 has no purchases and no city. That row exposes the edge cases later in the chapter.
CREATE TABLE customers (
id int PRIMARY KEY,
name text NOT NULL,
city text
);
CREATE TABLE purchases (
id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id int NOT NULL REFERENCES customers (id),
sku text NOT NULL,
qty int NOT NULL,
unit_price numeric(8,2) NOT NULL,
purchased_at timestamptz NOT NULL
);
INSERT INTO customers VALUES
(1, 'Ada', 'Oslo'),
(2, 'Grace', 'Bergen'),
(3, 'Linus', NULL);
INSERT INTO purchases (customer_id, sku, qty, unit_price, purchased_at) VALUES
(1, 'A1', 2, 10.00, '2026-11-01 09:00+00'),
(1, 'B7', 1, 22.50, '2026-11-03 14:30+00'),
(2, 'A1', 1, 10.00, '2026-11-02 11:15+00');The two building blocks
Two kinds of function build JSON:
- A scalar function builds one JSON value from the arguments of a single row.
jsonb_build_objectandjsonb_build_arrayare scalar functions. - An aggregate function combines many rows into one JSON value.
jsonb_aggandjsonb_object_aggare aggregates.
You nest the first kind inside the second kind to build documents with arrays of objects.
jsonb_build_object
jsonb_build_object takes an alternating list of keys and values and returns a jsonb object.
SELECT jsonb_build_object('id', id, 'name', name, 'city', city) AS doc
FROM customers
ORDER BY id;The result has three rows:
{"id": 1, "city": "Oslo", "name": "Ada"}
{"id": 2, "city": "Bergen", "name": "Grace"}
{"id": 3, "city": null, "name": "Linus"}The keys do not appear in the order you wrote them. A jsonb value does not keep key order. It stores keys sorted by length first, then by bytes. Use json_build_object if you need to preserve order, at the cost of the other jsonb advantages.
Linus has a SQL NULL city, and it becomes a JSON null. The key stays in the document. If you would rather omit null fields, wrap the call in jsonb_strip_nulls(...). That function removes null-valued keys at every nesting level, so use it only when you do not need explicit nulls anywhere in the document.
How values are converted
PostgreSQL converts each value according to its SQL type.
| SQL value | JSON result |
|---|---|
| `integer`, `numeric`, `float` | number |
| `text`, `varchar` | string |
| `boolean` | `true` or `false` |
| `NULL` | `null` |
| `timestamp`, `timestamptz`, `date` | ISO 8601 string |
| array such as `ARRAY['a','b']` | JSON array |
| `json` or `jsonb` value | embedded as is, not re-quoted |
| composite or row value | JSON object |
The following query shows several of these conversions at once. The timestamp text assumes the session time zone is UTC.
SELECT jsonb_build_object(
'n', 1.5,
'flag', true,
'ts', timestamptz '2026-11-01 09:00+00',
'tags', ARRAY['a', 'b'],
'none', NULL::text
);{"n": 1.5, "ts": "2026-11-01T09:00:00+00:00", "flag": true, "none": null, "tags": ["a", "b"]}The ts value depends on the session TimeZone setting, because a timestamptz is rendered in that zone. Pin the zone, or convert with AT TIME ZONE, if the output must be identical on every connection.
The embedding rule for json and jsonb values matters when you nest. If you pass a jsonb value, it becomes a child object. If you pass its text form, such as details::text, you get an escaped string instead of structure.
Rules and errors
- Keys must be non-null. A key is converted to text, so
jsonb_build_object(1, 'x')produces{"1": "x"}. - The argument count must be even.
jsonb_build_object('a')fails with an error that the argument list must have an even number of elements. - Duplicate keys collapse in
jsonb, and the last value wins.json_build_objectkeeps every pair.
SELECT json_build_object('a', 1, 'a', 2) AS as_json,
jsonb_build_object('a', 1, 'a', 2) AS as_jsonb;{"a" : 1, "a" : 2} | {"a": 2}A function call accepts at most 100 arguments, so one call can build roughly 50 pairs. For wider rows, use to_jsonb(row) as shown below, or pass an array with the VARIADIC keyword.
Related scalar builders
jsonb_build_array builds an array from a list of arguments of any types:
SELECT jsonb_build_array(1, 'two', NULL, true);
-- [1, "two", null, true]to_jsonb converts one value of any type, including a whole row. This is the shortest way to turn a table row into a document:
SELECT to_jsonb(c) AS doc,
to_jsonb(c) - 'city' AS without_city
FROM customers c
WHERE id = 1;The row alias c is used as a value here, and each column becomes a key. The - operator from the chapter on modifying jsonb then removes a key from the result. With to_jsonb(row) you pick up new columns automatically, which is convenient but means a later ALTER TABLE changes your output. List the keys explicitly with jsonb_build_object when the shape is a contract with a client.
jsonb_agg
jsonb_agg(expression) collects the values of expression from all rows in a group into one JSON array. Combine it with jsonb_build_object to get an array of objects:
SELECT jsonb_agg(
jsonb_build_object('sku', sku, 'qty', qty)
ORDER BY purchased_at
) AS items
FROM purchases
WHERE customer_id = 1;[{"qty": 2, "sku": "A1"}, {"qty": 1, "sku": "B7"}]Three details decide whether the result is correct:
- Order. An aggregate gives no ordering guarantee unless you write
ORDER BYinside the call, as above. AnORDER BYat the end of the query orders the output rows, not the array elements. - Empty input. If no rows reach the aggregate, the result is SQL
NULL, not[]. Wrap it withcoalesce(..., '[]'::jsonb)when the consumer expects an array. - NULL inputs. A
NULLargument becomes a JSONnullelement. It is not skipped.
You can also use DISTINCT (jsonb_agg(DISTINCT sku)) and a FILTER (WHERE ...) clause on the aggregate, like any other aggregate.
Nesting: one document per parent row
The common task is a parent document that carries its child rows. The direct way is a LEFT JOIN plus GROUP BY:
SELECT jsonb_build_object(
'id', c.id,
'name', c.name,
'purchases', coalesce(
jsonb_agg(
jsonb_build_object('sku', p.sku, 'qty', p.qty)
ORDER BY p.purchased_at
) FILTER (WHERE p.id IS NOT NULL),
'[]'::jsonb)
) AS doc
FROM customers c
LEFT JOIN purchases p ON p.customer_id = c.id
GROUP BY c.id, c.name
ORDER BY c.id;The FILTER (WHERE p.id IS NOT NULL) is necessary. A left join produces one row of NULLs for Linus, and without the filter he would get [{"qty": null, "sku": null}], a fake purchase. With the filter the aggregate sees no rows, returns NULL, and coalesce turns it into an empty array.
Avoiding row multiplication
The join approach breaks when you add a second child table. Joining customers to purchases and to, say, support tickets multiplies the rows: 2 purchases and 3 tickets give 6 joined rows, and each purchase appears 3 times in the aggregate. Aggregate each child table separately instead. A correlated LATERAL subquery does this cleanly:
SELECT jsonb_build_object(
'name', c.name,
'purchases', x.purchases
) AS doc
FROM customers c
CROSS JOIN LATERAL (
SELECT coalesce(
jsonb_agg(
jsonb_build_object('sku', p.sku, 'qty', p.qty)
ORDER BY p.purchased_at),
'[]'::jsonb) AS purchases
FROM purchases p
WHERE p.customer_id = c.id
) x
ORDER BY c.id;An aggregate query without GROUP BY always returns exactly one row, so the CROSS JOIN never drops a customer. Add one LATERAL subquery per child table. Each one aggregates only its own rows, so nothing is multiplied. Check performance with EXPLAIN on large tables. The subquery runs once per customer, so an index on purchases (customer_id) matters.
jsonb_object_agg
jsonb_object_agg(key, value) builds one object from many rows, with one key per row:
SELECT customer_id,
jsonb_object_agg(sku, qty) AS qty_by_sku
FROM purchases
GROUP BY customer_id
ORDER BY customer_id;1 | {"A1": 2, "B7": 1}
2 | {"A1": 1}The key must not be NULL. If a key repeats within a group, jsonb keeps only one value, and without an ordering you cannot say which. Collapse duplicates first, for example with a subquery that does GROUP BY customer_id, sku and sum(qty), and aggregate that result.
Common mistakes
Other points to watch:
- Numbers.
numericvalues keep their exact digits, butfloatvalues may print with rounding noise. Cast money tonumericbefore building. - Size. A
jsonbvalue is limited to about 255 MB, and building huge documents in memory is slow. Aggregate in pages when the result is large. - Typed output. Building JSON does not create a schema. If you read the document back with
->>, you must cast again, as covered earlier.
Summary table
| Function | Kind | Input | Output |
|---|---|---|---|
| `jsonb_build_object(k, v, ...)` | scalar | alternating keys and values | object |
| `jsonb_build_array(v, ...)` | scalar | any values | array |
| `to_jsonb(x)` | scalar | any value or row | matching JSON value |
| `jsonb_agg(x)` | aggregate | one value per row | array, `NULL` if no rows |
| `jsonb_object_agg(k, v)` | aggregate | key and value per row | object, `NULL` if no rows |
Exercise
Write a query that returns one row per customer with a jsonb document of the form {"name": ..., "total": ...}, where total is the sum of qty * unit_price over that customer's purchases. Customers with no purchases must show a total of 0.
Show answer
SELECT jsonbbuildobject('name', c.name, 'total', coalesce(sum(p.qty * p.unitprice), 0)) AS doc FROM customers c LEFT JOIN purchases p ON p.customerid = c.id GROUP BY c.id, c.name ORDER BY c.id; The LEFT JOIN keeps Linus, sum() returns NULL for him, and coalesce turns that into 0. Ada gets 42.50, Grace 10.00 and Linus 0.
Exercise
A query uses jsonbagg(jsonbbuild_object('sku', p.sku)) over a LEFT JOIN, and a customer with no purchases gets [{"sku": null}] instead of []. Fix it, and explain why the output was wrong.
Show answer
Add FILTER (WHERE p.id IS NOT NULL) to the aggregate and wrap it in coalesce(..., '[]'::jsonb). The LEFT JOIN yields one all-NULL row for a customer with no purchases. jsonbbuildobject turns that row into an object with a null value, and jsonbagg includes it. The filter removes the row before aggregation, jsonbagg then returns NULL, and coalesce replaces it with an empty array.
Exercise
Why does 'jsonbbuildobject('a', 1, 'a', 2)' return {"a": 2} while 'jsonbuildobject' with the same arguments returns both pairs?
Show answer
The jsonb type stores a parsed, deduplicated, sorted structure, so a repeated key keeps only the last value. The json type stores the text as written, so it keeps duplicates and the original order.