Add a root node to JSON output

By specifying the ROOT option in the FOR JSON query, you can add a single, top-level element to the JSON output. The following code shows this:

SELECT TOP (3) PersonID, FullName, EmailAddress, PhoneNumber 
FROM Application.People ORDER BY PersonID ASC FOR JSON AUTO, ROOT('Persons'); 

Here is the result:

{ 
   "Persons":[ 
      { 
         "PersonID":1, 
         "FullName":"Data Conversion Only" 
      }, 
      { 
         "PersonID":2, 
         "FullName":"Kayla Woodcock", 
         "EmailAddress":"kaylaw@wideworldimporters.com", 
         "PhoneNumber":"(415) 555-0102" 
      }, 
      { 
         "PersonID":3, 
         "FullName":"Hudson Onslow", 
         "EmailAddress":"hudsono@wideworldimporters.com", 
         "PhoneNumber":"(415) 555-0102" 
      } 
   ] 
} 

By specifying the root element, you have converted the outer array to a single complex property ...

Get SQL Server 2017 Developer's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.