Sub topic 7
Generating JSON with JSON_OBJECT and JSON_ARRAYAGG
Earlier chapters read JSON that was already stored. This chapter goes the other way. You build JSON from relational rows with JSON_OBJECT, JSON_ARRAY, JSON_ARRAYAGG and JSON_OBJECTAGG. This is how you return document-shaped results from normalized tables without storing a copy of them.
This chapter assumes you can write joins, correlated subqueries and GROUP BY queries. It also assumes you know the native JSON type from the chapter on JSON columns (Oracle Database 21c or later). RETURNING JSON needs 21c. The rest works on 19c if you return VARCHAR2 or CLOB.
The sample tables
The examples use two small normalized tables. They have the same shape as the ones the duality view chapters use, but different names, so the two sets of examples don't collide.
CREATE TABLE gen_department (
department_id NUMBER PRIMARY KEY,
name VARCHAR2(50) NOT NULL
);
CREATE TABLE gen_employee (
employee_id NUMBER PRIMARY KEY,
name VARCHAR2(50) NOT NULL,
department_id NUMBER REFERENCES gen_department (department_id)
);
INSERT INTO gen_department VALUES (10, 'Research');
INSERT INTO gen_department VALUES (20, 'Operations');
INSERT INTO gen_employee VALUES (100, 'Grace', 10);
INSERT INTO gen_employee VALUES (101, 'Alan', 10);
COMMIT;Department 20 has no employees. It is there to show how generation functions treat empty groups.
One object per row: JSON_OBJECT
JSON_OBJECT builds one JSON object from name/value pairs. Each pair is written 'key' VALUE expression. The shorter form 'key' : expression means the same thing.
SELECT JSON_OBJECT(
'employeeId' VALUE e.employee_id,
'name' VALUE e.name
) AS doc
FROM gen_employee e
ORDER BY e.employee_id;The query returns one row per employee:
{"employeeId":100,"name":"Grace"}
{"employeeId":101,"name":"Alan"}Oracle chooses the JSON type of each value from the SQL type of the expression. Numbers become JSON numbers and strings become JSON strings. Dates and timestamps become ISO 8601 strings.
If you want every column of a table, JSON_OBJECT(*) uses the column names as keys:
SELECT JSON_OBJECT(*) FROM gen_employee;The keys are the column names as Oracle stores them, which are uppercase unless you quoted the names when creating the table. The output looks like {"EMPLOYEE_ID":100,"NAME":"Grace","DEPARTMENT_ID":10}. This is handy for quick exports. For an API contract, name the keys yourself.
JSON_ARRAY is the array counterpart. It takes a list of values: JSON_ARRAY(1, 'two', e.name).
Many rows into one array: JSON_ARRAYAGG
JSON_ARRAYAGG is an aggregate function, like SUM or LISTAGG. It collects the values from many rows into one JSON array. You can give it an ORDER BY inside the parentheses to control the order of the elements.
SELECT JSON_ARRAYAGG(
JSON_OBJECT('employeeId' VALUE e.employee_id,
'name' VALUE e.name)
ORDER BY e.employee_id
RETURNING JSON
) AS employees
FROM gen_employee e;The result is a single value:
[{"employeeId":100,"name":"Grace"},{"employeeId":101,"name":"Alan"}]JSON_OBJECTAGG does the same for objects. It folds many rows into one object, using one column as the key and another as the value:
SELECT JSON_OBJECTAGG(KEY e.name VALUE e.employee_id RETURNING JSON) AS ids
FROM gen_employee e;Each key must be unique within the object, so use it only where the key column is unique.
Building nested documents
A document-shaped result usually has a parent object with an array of child objects. There are two common ways to build one. The diagram shows the data flow that both share.
Pattern 1: a correlated subquery
A scalar subquery in the VALUE position builds the child array for the current parent row. This is the clearest pattern and needs no GROUP BY.
SELECT JSON_OBJECT(
'_id' VALUE d.department_id,
'departmentName' VALUE d.name,
'employees' VALUE (
SELECT JSON_ARRAYAGG(
JSON_OBJECT('employeeId' VALUE e.employee_id,
'name' VALUE e.name)
ORDER BY e.employee_id
RETURNING JSON)
FROM gen_employee e
WHERE e.department_id = d.department_id)
RETURNING JSON
) AS doc
FROM gen_department d
ORDER BY d.department_id;For department 10 the document is:
{"_id":10,"departmentName":"Research","employees":[{"employeeId":100,"name":"Grace"},{"employeeId":101,"name":"Alan"}]}For department 20 the subquery finds no rows. An aggregate over zero rows returns NULL, not an empty array, so the document contains "employees":null.
Pattern 2: a join with GROUP BY
You can instead join the tables and aggregate. This works well when the parent has only a few fields, because you must list every parent column in GROUP BY.
SELECT JSON_OBJECT(
'_id' VALUE d.department_id,
'departmentName' VALUE d.name,
'employeeNames' VALUE JSON_ARRAYAGG(e.name ORDER BY e.name RETURNING JSON)
RETURNING JSON
) AS doc
FROM gen_department d
LEFT JOIN gen_employee e ON e.department_id = d.department_id
GROUP BY d.department_id, d.name
ORDER BY d.department_id;Here department 20 produces "employeeNames":[], because the outer join yields one row with a null name and JSON_ARRAYAGG drops null elements by default. Do not aggregate a whole JSON_OBJECT over an outer join this way. The object is built before aggregation, so the null row becomes {"employeeId":null,"name":null} and appears as a bogus element. Aggregate a plain column as above, or use the correlated subquery.
Controlling NULL handling
The generation functions differ in how they treat SQL NULL. This is a common source of surprises.
| Function | Default | Other options |
|---|---|---|
| `JSON_OBJECT` | `NULL ON NULL` (the key is kept, the value is JSON `null`) | `ABSENT ON NULL` omits the key |
| `JSON_ARRAY` | `ABSENT ON NULL` (null elements are dropped) | `NULL ON NULL` keeps them |
| `JSON_ARRAYAGG` | `ABSENT ON NULL` | `NULL ON NULL` |
| `JSON_OBJECTAGG` | `NULL ON NULL` | `ABSENT ON NULL` |
To leave out the employees key for an empty department instead of writing null, put ABSENT ON NULL in the outer JSON_OBJECT:
SELECT JSON_OBJECT(
'_id' VALUE d.department_id,
'employees' VALUE (
SELECT JSON_ARRAYAGG(e.name ORDER BY e.name RETURNING JSON)
FROM gen_employee e
WHERE e.department_id = d.department_id)
ABSENT ON NULL
RETURNING JSON
) AS doc
FROM gen_department d;Department 20 now returns {"_id":20}.
Return types and size limits
By default these functions return VARCHAR2(4000). A longer result raises an error such as ORA-40478 (output value too large). You have three choices:
RETURNING VARCHAR2(n)raises the limit up to the maximum string size configured for the database.RETURNING CLOBhandles large documents and keeps the output as text.RETURNING JSONproduces the native binary type. It has no 4000-byte limit and is the best choice if the result goes into aJSONcolumn or is queried again withJSON_VALUE.
Nesting generated JSON
When one generation function is an argument of another, the inner result must be treated as JSON, not as a string. If it is treated as a string, the outer function escapes the quotes and you get "[{\"name\":\"Grace\"}]". Two things prevent this:
- Give the inner function
RETURNING JSON, as in the examples above. - If the inner value is text, such as a
VARCHAR2orCLOBcolumn holding JSON, addFORMAT JSONafter it:'details' VALUE t.details_text FORMAT JSON.
Unnesting, then regenerating
Generation is the inverse of JSON_TABLE. A typical pipeline reads a stored document, flattens it, filters or joins it, and builds a new document. Use JSON_TABLE for the first step and the functions from this chapter for the last.
Common errors
- Forgetting
GROUP BYcolumns when combiningJSON_ARRAYAGGwith other selected columns raises ORA-00979 (not a GROUP BY expression). - Putting
ORDER BYoutside the aggregate leaves the array order unspecified. Put it insideJSON_ARRAYAGG(... ORDER BY ...). - Expecting
JSON_ARRAYAGGover no rows to return[]. It returnsNULL. - Using
JSON_OBJECTAGGwith duplicate keys. Keys must be unique unless you useWITH UNIQUE KEYSdeliberately to have Oracle raise an error.
Exercise
Write a query that returns, for each department, one JSON document with keys departmentName and employeeCount (a number). Departments with no employees must show a count of 0. Use gen_department and gen_employee.
Show answer
SELECT JSONOBJECT('departmentName' VALUE d.name, 'employeeCount' VALUE COUNT(e.employeeid) RETURNING JSON) AS doc FROM gendepartment d LEFT JOIN genemployee e ON e.departmentid = d.departmentid GROUP BY d.department_id, d.name; COUNT of a column ignores the null produced by the outer join, so department 20 gets 0.
Exercise
A query returns {"_id":20,"employees":null} for an empty department. Name two ways to change the result so that it does not contain a JSON null.
Show answer
Add ABSENT ON NULL to the outer JSON_OBJECT so the "employees" key is omitted. Or wrap the subquery so that an empty result becomes an empty array (for example by aggregating a plain column through a LEFT JOIN and GROUP BY, which yields []).