Lesson 3 of 4 JSON in SQL Databases

Building JSON Objects and Arrays in T-SQL

This lesson explains JSON_OBJECT, JSON_ARRAY, JSON_ARRAYAGG, JSON_OBJECTAGG and FOR JSON, and when to use each to produce JSON from rows.

Learning outcomes

After completing this lesson, you will be able to:

  • Explain how JSON_OBJECT and JSON_ARRAY build documents and handle NULL values.
  • Describe how JSON_ARRAYAGG aggregates rows into arrays.
  • Choose between the construction functions and FOR JSON.

JSON_OBJECT and JSON_ARRAY

JSON_OBJECT builds an object from 'key':value pairs, and JSON_ARRAY builds an array from a list of values. Both can be nested, so one expression can produce a complete document, and values are escaped correctly, which avoids the bugs and injection risks of building JSON by string concatenation. The null clause controls NULL values: NULL ON NULL writes null, while ABSENT ON NULL omits the property (the default for JSON_OBJECT is NULL ON NULL, and for JSON_ARRAY ABSENT ON NULL).

SELECT JSON_OBJECT(
           'id': p.ProductID,
           'name': p.Name,
           'price': p.ListPrice,
           'sizes': JSON_ARRAY('S', 'M', 'L'),
           'discontinued': p.DiscontinuedDate ABSENT ON NULL) AS ProductJson
FROM Catalog.Product AS p;
Spot the bug

Hand-built JSON

Exam skills 1.3.3

Find the lines that make this JSON construction unsafe or wrong.

Log in to try this activity Interactive activities are free with an account.

Aggregating rows into JSON

JSON_ARRAYAGG(expression ORDER BY ...) is an aggregate that collects the values of a group into one JSON array, and JSON_OBJECTAGG(key : value) collects key-value pairs into one object. With GROUP BY they produce one document per parent row, such as each order with its lines, without a subquery per row.

SELECT o.OrderID,
       JSON_OBJECT(
           'orderId': o.OrderID,
           'lines': JSON_ARRAYAGG(
                        JSON_OBJECT('product': l.ProductID, 'qty': l.Quantity)
                        ORDER BY l.LineNumber)) AS OrderJson
FROM Sales.Orders AS o
JOIN Sales.OrderLines AS l ON l.OrderID = o.OrderID
GROUP BY o.OrderID;

FOR JSON

FOR JSON PATH formats a whole result set as a JSON array, with property names taken from column aliases; aliases with dots, such as [price.amount], create nested objects, and a correlated subquery with FOR JSON nests a child array. WITHOUT_ARRAY_WRAPPER returns a single object, ROOT('name') wraps the array in an object, and INCLUDE_NULL_VALUES keeps NULL properties. FOR JSON AUTO derives nesting from the joins in the query. The choice between the approaches is summarized in the following table.

NeedUse
One JSON value inside a larger expression or payloadJSON_OBJECT and JSON_ARRAY
One array per group of rowsJSON_ARRAYAGG with GROUP BY
A whole query result as JSON for an APIFOR JSON PATH
Match the pairs

Choosing a JSON builder

Exam skills 1.3.3

Match each need with the T-SQL feature that meets it.

Log in to try this activity Interactive activities are free with an account.
Worked example

An API payload with nested lines

A procedure must return each of a customer's recent orders as one JSON document containing the order header and an array of its lines, ordered by line number. A previous version built the JSON with string concatenation and broke when product names contained quotes. What should the developer use?

Build the document with JSON_OBJECT for the header and JSON_ARRAYAGG(JSON_OBJECT(...) ORDER BY LineNumber) grouped by order, or with FOR JSON PATH and a nested subquery. These functions escape quotes and special characters correctly. Replacing quotes manually in the concatenated string treats the symptom and leaves other escaping problems, such as backslashes and control characters.

Check yourself

How do you omit properties whose values are NULL from JSON_OBJECT output?

Show answer

Add ABSENT ON NULL; the default for JSON_OBJECT is NULL ON NULL, which writes null.

Exam Tips

Remember for the exam

  • Build objects and arrays safely: JSON_OBJECT and JSON_ARRAY, never string concatenation.
  • Child rows into one array per parent: JSON_ARRAYAGG with GROUP BY.
  • Omit NULL properties: ABSENT ON NULL.
  • Whole result set as JSON: FOR JSON PATH (WITHOUT_ARRAY_WRAPPER for one object).